Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin 'until' fun creating IntRange garbage

Tags:

kotlin

I was using the until infix fun for my loop below

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

when profiling my code with YourKit I noticed that I had a huge amount of IntRange objects (about 2k/sec). enter image description here

When I switch the loop to use the int...int rangeTo directly it does not create any garbage.

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

Can someone please explain the difference between these two? From what I can tell Int.until simply returns 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_
}
like image 693
Jonathan Beaudoin Avatar asked Aug 31 '16 02:08

Jonathan Beaudoin


1 Answers

In the current version v1.0.4 the compiler optimises calls for rangeTo and downTo functions since they are the most common in for loops.

I think they'll optimises until away some time soon.

Here is the relevant issue ticket: https://youtrack.jetbrains.com/issue/KT-9900. Feel free to vote it up.

like image 142
voddan Avatar answered Oct 24 '22 03:10

voddan