Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

performance - Slow range forEach in Kotlin

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...