When to use sequences in Kotlin - Time & Space Complexity
We want to understand how using sequences affects the time it takes to process data in Kotlin.
When do sequences help with performance as data grows?
Analyze the time complexity of the following Kotlin code using sequences.
val numbers = (1..n).toList()
val result = numbers.asSequence()
.filter { it % 2 == 0 }
.map { it * 2 }
.toList()
This code filters even numbers and doubles them using a sequence before collecting results.
Look at the loops and operations that repeat over the data.
- Primary operation: Filtering and mapping each element in the sequence.
- How many times: Each element is visited once during the combined operations.
As the input size grows, the number of operations grows roughly the same as the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and 10 doubles |
| 100 | About 100 checks and 100 doubles |
| 1000 | About 1000 checks and 1000 doubles |
Pattern observation: The work grows linearly with input size because each element is processed once.
Time Complexity: O(n)
This means the time to finish grows in direct proportion to how many items you have.
[X] Wrong: "Sequences always make the code faster no matter what."
[OK] Correct: Sequences help by processing items lazily, but if you only do simple operations or have small data, the overhead might not be worth it.
Knowing when to use sequences shows you understand how to handle data efficiently as it grows, a useful skill in many coding tasks.
"What if we replaced the sequence with a regular list chain of filter and map? How would the time complexity change?"