Slow range forEach in Kotlin

前端 未结 3 1517
南方客
南方客 2020-12-18 10:51

I used the following code to measure performance of different syntax constructions in Kotlin

fun time(what: String, body: () -> Int) {
    val start =          


        
3条回答
  •  执念已碎
    2020-12-18 11:26

    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.forEach(...) - these are two different calls.

    I guess the Kotlin compiler knows to optimize IntArray.forEach(...), but not Iterable.forEach(...).

提交回复
热议问题