I used the following code to measure performance of different syntax constructions in Kotlin
fun time(what: String, body: () -> Int) {
val start =
From documentation:
A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.
forEach
as you can see at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each.html is special-cased for arrays, but has a single implementations for all Iterable
s, so it needs to create an iterator.
Thanks for this code. I was more interested in the performance difference between array and list and was a bit shocked to have 6 times as long running time. I thought the list is only slow in creation.
Above runtimes on my machine or comparison:
for in range: 55
for in collection: 57
forEach: 55
range forEach: 223
sum: 57
//code change
//val arr = IntArray(n) { rand.nextInt() }
val arr = List(n) { rand.nextInt() }
for in range: 383
for in collection: 367
forEach: 367
range forEach: 486
sum: 371
The most interesting comparison is probably between these 2 cases:
Case A: taking 86 ms
time("forEach") {
var sum = 0
arr.forEach { sum += it }
sum
}
Case B: taking 294 ms
time("range forEach") {
var sum = 0
(0 until n).forEach { sum += arr[it] }
sum
}
While case A is actually calling IntArray.forEach(...)
case B is calling Iterable<T>.forEach(...)
- these are two different calls.
I guess the Kotlin compiler knows to optimize IntArray.forEach(...)
, but not Iterable<T>.forEach(...)
.