kotlin

Is Kotlin's range checking is efficent?


In Kotlin

val x = 50000
if (x in 1..100000) {
    println(x)
}

I think the above code readability is better than code with inequality. But I wonder the performence of that code is also good.

If it literally iterate 100000 times, it seems too stupid.

Is it equal to (1 <= x && x <= 100000) for performance?


Solution

  • The .. operator calls the rangeTo operator function, which creates a IntRange object. The in operator then calls the contains operator function, which is implemented as:

    public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive
    

    Therefore, it does not loop 100000 times, and it is the same as

    1 <= x && x <= 100000
    

    except that it also creates a new IntRange object, which won't really matter in the grand scheme of things.

    On the JVM at least, the compiler can even inline this comparison, so not even an IntRange object will be created.