Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Kotlin's range checking is efficent?

Tags:

kotlin

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?

like image 824
Jimmy Choi Avatar asked Oct 12 '25 10:10

Jimmy Choi


1 Answers

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.

like image 119
Sweeper Avatar answered Oct 14 '25 23:10

Sweeper