Slow range forEach in Kotlin

前端 未结 3 1518
南方客
南方客 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题