Declarative Kotlin: Lists, Sequences and RxJava

Observable.from(text.split(SEPARATOR))
.map(line -> line.trim() + NEW_LINE)
.toList()
.toBlocking()
.single()
text.split(SEPARATOR)
.map { it.trim() + NEW_LINE }

Simple Case

Observable.range(0, 1_000_000)
.map { it + 1 }
.blockingLast() // 863ms
(1..1_000_000)
.map { it + 1 }
.last() // 755ms

Multiple Operations

Observable.range(0, 1_000_000)
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.blockingLast() // 2843ms
(1..1_000_000)
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.map { it + 1 }
.last() // 3439ms

Unnecessary Work

Observable.range(0, 1_000_000)
.map { it + 1 }
.blockingFirst() // 104ms
(1..1_000_000)
.map { it + 1 }
.first() // 678ms

Sequence to the rescue!

(1..1_000_000)
.asSequence()
.map { it + 1 }
.last()

You should avoid passing or returning Sequences from your functions as other users of the function might iterate over the Sequences multiple times which is wasteful!

Not JITed benchmark

EDIT:

JITed benchmark
Unnecessary Work benchmark

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tomek Polański

Tomek Polański

Passionate mobile developer. One thing I like more than learning new things: sharing them