Derek Peirce
10/26/2025, 7:51 AMfor (i in 0 until 5) {
println(i)
}
this compiles into Java:
for(int i = 0; i < 5; ++i) {
System.out.println(i);
}
However, revising it to:
(0 until 5).forEach { i ->
println(i)
}
turns it into the vastly less efficient:
Iterable $this$forEach$iv = (Iterable)RangesKt.until(0, 5);
int $i$f$forEach = 0;
Iterator var2 = $this$forEach$iv.iterator();
while(var2.hasNext()) {
int element$iv = ((IntIterator)var2).nextInt();
int var5 = 0;
System.out.println(element$iv);
}
Could the compiler be optimized to recognize when it is creating an Iterator from a well-known Range, whether that's for forEach, forEachIndexed, all, etc., and use the more efficient for-loop instead?
Adjusting the above code to use the first form instead of the second form is trivial enough, but optimizing a call like:
(0 until 10).all { evaluatesCorrectly(it) }
ends up looking something like:
run {
for (i in 0 until 10) {
if (!evaluatesCorrectly(i))
return@run false
}
true
}
which is more efficient, but not nearly as concise.Joffrey
10/26/2025, 8:13 AMrepeat(5) { println(it) } do by the way? (I'm AFK so I can't check). It would be more idiomatic than creating a range from 0 just to iterate on it.Joffrey
10/26/2025, 8:14 AMall, thoughephemient
10/26/2025, 8:17 AMephemient
10/26/2025, 8:18 AMDerek Peirce
10/26/2025, 8:20 AMrepeat uses for-loops as one would expect, but I'm using 0 until 5 as a placeholder example here.ephemient
10/26/2025, 8:21 AMDerek Peirce
10/26/2025, 8:24 AMfor-loops at bytecode postprocessing stage," is that particular decision tracked anywhere or is it completely in limbo?ephemient
10/26/2025, 8:25 AMmikehearn
10/30/2025, 3:30 PMDerek Peirce
11/11/2025, 10:39 PMfun rangeWithForLoop(blackhole: Blackhole) {
for (i in 0 until 1_000_000) {
blackhole.consume(i)
}
}
fun rangeWithForEach(blackhole: Blackhole) {
(0 until 1_000_000).forEach {
blackhole.consume(it)
}
}
I got these results:
Benchmark Mode Cnt Score Error Units
RangeBenchmark.rangeForEach avgt 20 1.306 ± 0.026 ms/op
RangeBenchmark.rangeForLoop avgt 20 1.017 ± 0.083 ms/op
so it is less efficient even after JITC.