I used the following code to measure performance of different syntax constructions in Kotlin
fun time(what: String, body: () -> Int) {
val start =
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
- these are two different calls.
I guess the Kotlin compiler knows to optimize IntArray.forEach(...)
, but not Iterable
.