Iterating through range created with until is faster than when the range is created with `..`

Hello,

I came across a strange issue, I ran the following two functions:

    fun test1() {
        var x = 1f
        var y = 0

        for (a in 1 .. 1000) {
            for (b in 1 .. 1000) {
                for (c in 1 .. 1000) {
                    x *= -1f
                    y += 1
                }
            }
        }
    }

and

fun test1() {
    var x = 1f
    var y = 0

    for (a in 1 until 1001) {
        for (b in 1 until 1001) {
            for (c in 1 until 1001) {
                x *= -1f
                y += 1
            }
        }
    }
}

The first one executed in 3408.3726 ms, and the second one in 1643.2031 ms.
Both functions were executed in JVM and were measured in identical way, using System.nanoTime().

As you can see the two functions have the same meaning, run through equal number of cycles, but the execution time of the first one is doubled compared to the second one.

I ran the same tests in Android Studio and used the profiler to see if the first one does something strange (like unboxing), but there was nothing strange there.

I hope this is a bug in the current version, or someone can give me a reasonable explanation why this happens.

Thank you,
Alex

JMH is short for Java Microbenchmark Harness . JMH is a toolkit that helps you implement Java microbenchmarks correctly. JMH is developed by the same people who implement the Java virtual machine, so these guys know what they are doing.

Continue here

Thank you for your suggestion. However, although not perfect, my measurements are valid. Testing with profiler confirmed that too.

Interesting!
Can you share the test code and your results?

Here is a link to the code: https://gist.github.com/alexanderpp/9b63b0a242b4fc5f127aadd15278f4e3

And the results:

Result using ‘…’: 3265.1084 ms.
Result using ‘until’: 1376.2533 ms.

Result using ‘until’: 1376.5824 ms.
Result using ‘…’: 3022.0647 ms.

Ok, now I can answer to you.

There is no bug, performances of .. and until are exactly the same.

Wrong tests lead to wrong conclusions.

Perfect, can you please explain yourself?

1 Like

Let’s just run it 10 times for example:

Result using 'until': 1670.9379 ms.
Result using '..': 4108.9033 ms.
Result using 'until': 2162.4143 ms.
Result using '..': 3937.515 ms.
Result using 'until': 2223.241 ms.
Result using '..': 1828.7341 ms.
Result using 'until': 2132.3528 ms.
Result using '..': 2117.1216 ms.
Result using 'until': 1763.558 ms.
Result using '..': 1985.4816 ms.
Result using 'until': 2236.7175 ms.
Result using '..': 1699.5599 ms.
Result using 'until': 1663.6581 ms.
Result using '..': 1923.1389 ms.
Result using 'until': 2268.4497 ms.
Result using '..': 1975.0752 ms.
Result using 'until': 1989.1061 ms.
Result using '..': 1847.7081 ms.
Result using 'until': 1815.6927 ms.
Result using '..': 1863.9408 ms.
Result using 'until': 1711.151 ms.
Result using '..': 1709.0033 ms.