June 2018
Intermediate to advanced
316 pages
6h 34m
English
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_000val array = Array(1_000) { it }@Benchmarkfun rangeLoop(blackhole: Blackhole) { range.forEach { blackhole.consume(it) }}@Benchmarkfun rangeSequenceLoop(blackhole: ...
Read now
Unlock full access