I used the following code to measure performance of different syntax constructions in Kotlin
fun time(what: String, body: () -> Int) {
val start = System.currentTimeMillis()
var sum = 0
repeat(10) {
sum += body()
}
val end = System.currentTimeMillis()
println("$what: ${(end - start) / 10}")
}
val n = 200000000
val rand = Random()
val arr = IntArray(n) { rand.nextInt() }
time("for in range") {
var sum = 0
for (i in (0 until n))
sum += arr[i]
sum
}
time("for in collection") {
var sum = 0
for (x in arr)
sum += x
sum
}
time("forEach") {
var sum = 0
arr.forEach { sum += it }
sum
}
time("range forEach") {
var sum = 0
(0 until n).forEach { sum += arr[it] }
sum
}
time("sum") {
arr.sum()
}
And that is the result I got:
for in range: 84
for in collection: 83
forEach: 86
range forEach: 294
sum: 83
So my question is: Why is range forEach much slower that other syntax constructions?
It seems to me that compiler may generate equal bytecode in all cases (but does not in case of "range forEach")