Lazy collections help your program run faster by doing work only when needed. They save time and memory by not processing everything at once.
0
0
Lazy collections for performance in Swift
Introduction
When you have a big list but only need some results.
When you want to save memory by not creating big temporary lists.
When you want to chain many operations without slowing down your app.
When you want to improve performance in loops or filters.
When you want to delay work until the last moment.
Syntax
Swift
let lazyCollection = collection.lazy // Example: let lazyNumbers = numbers.lazy.map { $0 * 2 }
Use .lazy on any collection to make it lazy.
Lazy collections only do work when you ask for the results.
Examples
This creates a lazy map that doubles numbers but does not run it yet.
Swift
let numbers = [1, 2, 3, 4, 5] let lazyNumbers = numbers.lazy.map { $0 * 2 } print(type(of: lazyNumbers))
This filters even numbers lazily and prints them one by one.
Swift
let numbers = [1, 2, 3, 4, 5] let lazyFiltered = numbers.lazy.filter { $0 % 2 == 0 } for num in lazyFiltered { print(num) }
This multiplies numbers by 3 lazily and takes only the first 3 results.
Swift
let numbers = [1, 2, 3, 4, 5] let firstThree = numbers.lazy.map { $0 * 3 }.prefix(3) print(Array(firstThree))
Sample Program
This program shows how lazy collections avoid creating big arrays right away. It prints the count of doubled numbers and then prints the first five doubled numbers using lazy evaluation.
Swift
let numbers = Array(1...1_000_000) // Without lazy: creates a big array immediately let doubled = numbers.map { $0 * 2 } print("Doubled count: \(doubled.count)") // With lazy: does not create big array until needed let lazyDoubled = numbers.lazy.map { $0 * 2 } // Take first 5 doubled numbers let firstFive = lazyDoubled.prefix(5) print("First five doubled: \(Array(firstFive))")
OutputSuccess
Important Notes
Lazy collections are great for big data but might be slower for small data because of overhead.
Use Array() to convert lazy results back to a normal array when needed.
Lazy collections work well with chaining multiple operations like map, filter, and prefix.
Summary
Lazy collections delay work until results are needed.
They improve performance and save memory for big data.
Use .lazy on collections to make them lazy.