科特林各地区的射程较慢 [英] Slow range forEach in Kotlin

查看:97
本文介绍了科特林各地区的射程较慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码来衡量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()
}

这就是我得到的结果:

范围内的84:
供集合中使用:83
forEach:86
每个范围:294
总和:83

for in range: 84
for in collection: 83
forEach: 86
range forEach: 294
sum: 83

所以我的问题是:为什么forforEach的范围比其他语法构造要慢得多?
在我看来,编译器在所有情况下都可以生成相等的字节码(但在"range forEach"的情况下则不会)

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

推荐答案

来自文档:

在范围或数组上的for循环已编译到不创建迭代器对象的基于索引的循环.

A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.

您可以在 https上看到的

forEach ://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each.html 是数组的特例,但是对所有Iterable都有单个实现,因此需要创建一个迭代器.

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.

这篇关于科特林各地区的射程较慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆