Lazy collections for performance in Swift - Time & Space Complexity
When using lazy collections, we want to see how the program's work changes as the input grows.
We ask: Does laziness make the program faster or slower as we handle more items?
Analyze the time complexity of the following code snippet.
let lazySquares = (1...n).lazy.map { $0 * $0 }
for square in lazySquares.prefix(5) {
print(square)
}
This code creates a lazy collection of squares from the numbers 1 to n, then prints only the first 5 squares.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating squares for only the first 5 numbers.
- How many times: Exactly 5 times, no matter how big n is.
Even if the input grows, the program only calculates 5 squares.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 calculations |
| 100 | 5 calculations |
| 1000 | 5 calculations |
Pattern observation: The work stays the same even as input grows because of laziness.
Time Complexity: O(1)
This means the program does a fixed amount of work regardless of input size.
[X] Wrong: "Lazy collections always process the entire list."
[OK] Correct: Lazy collections only do work when needed, so if you take a small part, only that part is processed.
Understanding lazy collections helps you write efficient code that saves time by doing less work when possible.
"What if we removed the prefix(5) and printed all squares? How would the time complexity change?"