Streams are lazy, collections are not

Be careful with those functions on large collections, though. Most of them will copy the collection for the sake of immutability.

Functions starting with as won't do that, though:

// Returns a view, no copy here
(1..10).toList().asReversed()

// Same here
(1..10).toList().asSequence()

To understand the difference, check the following code:

val numbers = (1..1_000_000).toList()
println
(measureTimeMillis {
numbers.stream().map {
it * it
}
}) // ~2ms

println(measureTimeMillis {
numbers.map {
it * it
}
}) // ~19ms

You'll notice that code using stream() actually never executes. Streams, being lazy, wait for a terminating function call. Functions on collections, on the other hand, execute one after the other.

If we add the terminating call though, we'll see totally different numbers:

println(measureTimeMillis {
numbers.stream().map {
it * it
}.toList()
}) // ~70ms

Converting from the stream back to the list is an expensive operation. Take those points into consideration when deciding which approach to use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.32