In Kotlin, how does a
Sequence differ from an
Can you think of any scenarios where a
Sequence would perform better than an
Sequence is a different container type in Kotlin. It has the same functions as
List) but handles these functions in a “multi step” way.
- Basically an Iterable will do each chained function like filter, map, etc on the entire Iterable before moving to the next function in the chain.
- A Sequence will do each function in the chain on each element of the Sequence before moving on to the next element.
When to use a
- Many or expensive operations to perform on a collection.
- When processing can short circuit. (end early because a result is found)
- The operation is stateless.
- The collection is smaller.
When to use
- When collecting the results (
- The operation is stateful.
- The collection is larger.
Stateful - other collections are needed to perform the operation
Stateless - no other collections needed to perform an operation