Slow range forEach in Kotlin

2019-04-10 21:30发布

问题:

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")

回答1:

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 Iterables, so it needs to create an iterator.



回答2:

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(...).