Slow range forEach in Kotlin

前端 未结 3 1515
南方客
南方客 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:19

    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.

    0 讨论(0)
  • 2020-12-18 11:22

    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

    0 讨论(0)
  • 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<T>.forEach(...) - these are two different calls.

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

    0 讨论(0)
提交回复
热议问题