Last active
March 10, 2026 15:44
-
-
Save lppedd/2d24500f1ca4bb90ae9fc49de271143a to your computer and use it in GitHub Desktop.
CharArray to String benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlinx.benchmark.* | |
| import kotlin.math.min | |
| @State(Scope.Benchmark) | |
| @BenchmarkMode(Mode.Throughput) | |
| @Warmup(iterations = 4, time = 5, timeUnit = BenchmarkTimeUnit.SECONDS) | |
| @Measurement(iterations = 4, time = 5, timeUnit = BenchmarkTimeUnit.SECONDS) | |
| public class CharArrayToStringBenchmark { | |
| private val array = CharArray(1000000) { | |
| when (it) { | |
| 0 -> 55356.toChar() | |
| 1 -> 57091.toChar() | |
| 2 -> 'c' | |
| 3 -> 'n' | |
| else -> ('a'..'z').random() | |
| } | |
| } | |
| @Benchmark | |
| public fun concatenation(blackhole: Blackhole) { | |
| val str = array.concatToString() | |
| blackhole.consume(str) | |
| } | |
| @Benchmark | |
| public fun chunking1024(blackhole: Blackhole) { | |
| val str = array.chunkedConcatToString(1024) | |
| blackhole.consume(str) | |
| } | |
| @Benchmark | |
| public fun chunking2048(blackhole: Blackhole) { | |
| val str = array.chunkedConcatToString(2048) | |
| blackhole.consume(str) | |
| } | |
| @Benchmark | |
| public fun chunking4096(blackhole: Blackhole) { | |
| val str = array.chunkedConcatToString(4096) | |
| blackhole.consume(str) | |
| } | |
| @Benchmark | |
| public fun chunking8192(blackhole: Blackhole) { | |
| val str = array.chunkedConcatToString(8192) | |
| blackhole.consume(str) | |
| } | |
| @Benchmark | |
| public fun chunking16384(blackhole: Blackhole) { | |
| val str = array.chunkedConcatToString(16384) | |
| blackhole.consume(str) | |
| } | |
| private fun CharArray.chunkedConcatToString(chunkSize: Int): String { | |
| if (this.size <= chunkSize) { | |
| return js("String").fromCharCode.apply(null, this) | |
| } | |
| var str = "" | |
| var start = 0 | |
| while (start < this.size) { | |
| val end = min(start + chunkSize, this.size) | |
| val chunk = this.asDynamic().subarray(start, end) | |
| str += js("String").fromCharCode.apply(null, chunk) | |
| start = end | |
| } | |
| return str | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment