Skip to content

Instantly share code, notes, and snippets.

@lppedd
Last active March 11, 2026 23:34
Show Gist options
  • Select an option

  • Save lppedd/6548652d5687de69474033cb8d6caa8d to your computer and use it in GitHub Desktop.

Select an option

Save lppedd/6548652d5687de69474033cb8d6caa8d to your computer and use it in GitHub Desktop.
TypedArray benchmarks
import kotlinx.benchmark.*
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 4, time = 5, timeUnit = BenchmarkTimeUnit.SECONDS)
@Measurement(iterations = 4, time = 5, timeUnit = BenchmarkTimeUnit.SECONDS)
public class ByteArrayBenchmark {
private val fromArray: ByteArray
@Param("15", "100", "1000", "5000", "15000", "100000", "1000000")
public var newSize: Int = 0
public constructor() {
val size = 10000
val range = 0..255
val array = ByteArray(size)
for (i in 0..<size) {
array[i] = range.random().toByte()
}
fromArray = array
}
@Benchmark
public fun typedArraySet(blackhole: Blackhole) {
val size = fromArray.size
val toArray = when {
newSize < 16 || size < 16 -> ktFillFrom(fromArray, ByteArray(newSize))
newSize > size -> ByteArray(newSize).also { copy ->
copy.asDynamic().set(fromArray, 0)
}
else -> fromArray.asDynamic().slice(0, newSize)
}
blackhole.consume(toArray.unsafeCast<Any>())
}
@Benchmark
public fun fillFrom(blackhole: Blackhole) {
val toArray = ktFillFrom(fromArray, ByteArray(newSize))
blackhole.consume(toArray)
}
private fun ktFillFrom(src: dynamic, dst: dynamic): ByteArray {
val srcLen: Int = src.length
val dstLen: Int = dst.length
var index: Int = 0
val arr = dst.unsafeCast<Array<Any?>>()
while (index < srcLen && index < dstLen) {
arr[index] = src[index]
index++
}
return dst
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment