Ji Sungbin
01/22/2023, 8:27 AMnext()
operation. (stdlib api transforms to Iterator) (next()
implementation code: ArrayList.java)
But sometimes the stdlib api comes out faster. At higher numbers, the stdlib api is faster in most cases. Why is this result occurring?
I’ll post the benchmarking code I used in a thread.suspend fun main() = coroutineScope {
val times = List(/*100_000*/ 2_000_000_000) {} as ArrayList<Unit>
val decimal = DecimalFormat("#,###")
launch {
var average = 0L
launch {
repeat(10) { fastCount ->
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
average += measureNanoTime {
var value = 0
times.fastForEach {
value++
}
}.also { result ->
println("[$fastCount] Collections Fast API: ${result}ns")
}
}
}
}.join()
println("[AVERAGE] Collections Fast API: ${decimal.format(average / 10)}ns")
}
launch {
var average = 0L
launch {
repeat(10) { normalCount ->
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
average += measureNanoTime {
var value = 0
times.forEach {
value++
}
}.also { result ->
println("[$normalCount] Collections Normal API: ${result}ns")
}
}
}
}.join()
println("[AVERAGE] Collections Normal API: ${decimal.format(average / 10)}ns")
}
Unit
}
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
contract { callsInPlace(action) }
for (index in indices) {
val item = get(index)
action(item)
}
}
ephemient
01/22/2023, 6:06 PMJi Sungbin
01/22/2023, 6:11 PMephemient
01/22/2023, 6:14 PMDecimalFormat
which is JVM-onlyJi Sungbin
01/22/2023, 6:18 PMephemient
01/22/2023, 6:20 PMList.iterator()
vs List.get()
is entirely down to the Java implementationJi Sungbin
01/22/2023, 6:35 PM