Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering High Performance with Kotlin

You're reading from   Mastering High Performance with Kotlin Overcome performance difficulties in Kotlin with a range of exciting techniques and solutions

Arrow left icon
Product type Paperback
Published in Jun 2018
Publisher Packt
ISBN-13 9781788996648
Length 316 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Igor Kucherenko Igor Kucherenko
Author Profile Icon Igor Kucherenko
Igor Kucherenko
Arrow right icon
View More author details
Toc

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)
...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image