Skip to content

Instantly share code, notes, and snippets.

@lppedd
Last active March 10, 2026 15:44
Show Gist options
  • Select an option

  • Save lppedd/2d24500f1ca4bb90ae9fc49de271143a to your computer and use it in GitHub Desktop.

Select an option

Save lppedd/2d24500f1ca4bb90ae9fc49de271143a to your computer and use it in GitHub Desktop.
CharArray to String benchmark
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