https://kotlinlang.org logo
#announcements
Title
# announcements
h

Hexa

06/10/2019, 8:53 AM
is there a hard and fast rule of when to use
sequence
vs when to use
streams
? i know sequence is for processing large collection of data, but is there any reason why can't I use it to process small amount of data?
g

gildor

06/10/2019, 8:55 AM
They are pretty similar, but for example Java streams also support parallel execution
why can’t I use it to process small amount of data
Because eager collection operators will be faster for small collections
👍 1
also it depends on case
for example sequence is better with filter etc, but if you just do map and then convert to list you save nothing, it will be actually slower than eager list.map{}
k

karelpeeters

06/10/2019, 9:44 AM
Which is unfortunate, it would be great if chains of
Sequence
operations would be compiled to normal for loops as well.
g

gildor

06/10/2019, 9:46 AM
How would it be possible?
Sequence is lazy, you cannot inline operators
k

karelpeeters

06/10/2019, 9:50 AM
Yes, it would require a lot more compiler support and special casing, I understand why they didn't do that. But something like
Copy code
val res = list.filter(::f).filter(::g).flatMap(::h).toList()
should be compilable to
Copy code
val res = mutableListOf()
for (e in list) {
    if (!f(e)) continue
    if (!g(e)) continue
    for (n in h(e))
        res += n
}
Or are there exceptions I'm not aware of?
g

gildor

06/10/2019, 9:51 AM
yes, probably, but it looks as very complicated optimization for me, but I’m not an expert in compiler optimisations
k

karelpeeters

06/10/2019, 9:52 AM
I don't think this is a "special case", I very often want to do chained operations to transform a list into another list and I'm always faced with the choice of doing eager, using sequences or just writing the for myself.
g

gildor

06/10/2019, 9:52 AM
also probably such case maybe more efficient than collection operator
k

karelpeeters

06/10/2019, 9:53 AM
What do you mean?
g

gildor

06/10/2019, 9:53 AM
I mean if you have 2 filters, just use sequence %)
I agree, that in some cases it can be optimized by compiler
k

karelpeeters

06/10/2019, 9:54 AM
Yeah I usually end up writing a single
filter
with
&&
but that breaks down when you have something like
filter.map.filter
. Then I just start abusing
mapNotNull
, it's an unfortunate situation.
I think most cases should be optimizable by the compiler, how often do sequences actually leak outside a function?
Maybe I should just write C++ instead simple smile
g

gildor

06/10/2019, 10:01 AM
A lot of things may be optimized by the compiler, it’s all about priority. You can do complicated optimisation that will not give significant performance gain in 99% cases
k

karelpeeters

06/10/2019, 10:02 AM
Yeah I agree, I understand why the compiler doesn't do this.