Lazy map and filter
Chain lazy transforms without intermediate arrays.
Intermediate Arrays
Eager chains allocate a fresh array between every step. filter().map() on a big array builds two full arrays even though you may want only a few elements.
The Eager Allocation
Two intermediate arrays are created here:
let nums = Array(1...6)
let result = nums
.filter { $0 % 2 == 0 } // builds [2, 4, 6]
.map { $0 * 10 } // builds [20, 40, 60]
print(result) // [20, 40, 60]All lessons in this course
- The lazy Property
- Lazy map and filter
- Lazy vs Eager Trade-offs
- Building Custom Lazy Sequences