Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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

Collections

Always prefer read-only view collections over mutable ones. Since read-only view collections can't be changed, you can prevent a lot of bugs that relate to multithreading and state inconsistency. If you need to iterate elements of an ArrayList, consider the while loop:

inline fun <reified T> List<T>.foreach(crossinline invoke: (T) -> Unit): Unit {
val size = size
var i = 0
while (i < size) {
invoke(get(i))
i ++
}
}

Sequences can improve performance significantly, especially if you use methods such as first:

@Benchmark
fun sequence() = (0..1_000_000)
.asSequence()
.filter { it % 2 == 0 }
.map { it * it }
.first()
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 AU $24.99/month. Cancel anytime