Kotlin'直到'有趣的创建IntRange垃圾

时间:2016-08-31 02:17:06

标签: kotlin

我在下面的循环中使用了until infix fun

for (x in 0 until bodies.size) bodies[x]()

使用YourKit分析我的代码时,我注意到我有大量的IntRange对象(大约2k / sec)。 enter image description here

当我将循环切换为直接使用int...int rangeTo时,它不会产生任何垃圾。

for (x in 0..bodies.size-1) bodies[x]()

有人可以解释这两者之间的区别吗?据我所知,Int.until只需返回this .. to

public infix fun Int.until(to: Int): IntRange {
    val to_  = (to.toLong() - 1).toInt()
    if (to_ > to) throw IllegalArgumentException("The to argument value '$to' was too small.")
    return this .. to_
}

1 个答案:

答案 0 :(得分:5)

在当前版本v1.0.4中,编译器优化对rangeTodownTo函数的调用,因为它们是for循环中最常见的。

我认为他们会在不久的将来优化until

以下是相关问题单:https://youtrack.jetbrains.com/issue/KT-9900。 随意投票。