Range benchmarking
Since the IntRange
class inherits from the IntProgression
class which, in turn, implements the Iterable
interface, we can invoke the forEach
function:
(0..10).forEach { }
Decompiled to Java, the code looks like this:
public static final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); byte var1 = 0; Iterable $receiver$iv = (Iterable)(new IntRange(var1, 10)); int element$iv; for(Iterator var2 = $receiver$iv.iterator(); var2.hasNext(); element$iv = ((IntIterator)var2).nextInt()) { ; } }
Let's write it and run some benchmarks:
val range = 0..1_000 val array = Array(1_000) { it } @Benchmark fun rangeLoop(blackhole: Blackhole) { range.forEach { blackhole.consume(it) } } @Benchmark fun rangeSequenceLoop(blackhole: Blackhole) { range.asSequence().forEach { blackhole.consume(it) } } @Benchmark fun arrayLoop(blackhole: Blackhole) { array.forEach { blackhole.consume(it) } } @Benchmark fun arraySequenceLoop(blackhole: Blackhole...