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_000val array = Array(1_000) { it }@Benchmarkfun rangeLoop(blackhole: Blackhole) {    range.forEach {        blackhole.consume(it)    }}@Benchmarkfun rangeSequenceLoop(blackhole: ...

Get Mastering High Performance with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.