I think there is a common misconception that sequences are “just faster”. Depending on the case they could be faster or they could be slower.
As you said yourself, sequences involves additional overhead. Operators pass items between them which requires a lot of function calls. Operations on collections are simpler to implement and they are fully inlined.
Some collection operators like map()
know the size of the resulting collection upfront, so they can reserve a specific amount of space. Sequences can’t do that. You are concerned about just a single data copying, but remember that if you create an empty list and add 1000 items to it, you actually copy the data 12 times just to grow the list (but not all items for each grow).
There are use cases when sequences are a clear winner. Most importantly, if the data is too big to keep it all in the memory at once. Or if we operate on lazily generated and possibly infinite sequences. Intuition tells me that e.g. flatMap()
followed by filter()
that ignores most of items should be also faster with sequences, but I’m not sure about this. But generally speaking: no, sequences are not faster.
Also, there is a very interesting topic here on what kind of optimizations we could add to the language to overcome current performance problems of sequences and get advantages of both worlds.
P.S.
You can’t really measure the performance in Java like this. It gives almost meaningless results. Use JMH instead.