When to Choose Lazy vs. Eager
You'll learn when to use lazy sequences (generators) versus eager evaluation (arrays), and the trade-offs each approach brings.
The Core Decision
Lazy sequences (generators) compute values on demand, one at a time. Eager evaluation (arrays) computes everything upfront, creating the full result immediately. Both have their place—your choice depends on the problem at hand.
When Lazy Shines
Use lazy sequences when:
- Working with large datasets: Avoid loading millions of items into memory at once
- Building pipelines: Chain multiple transformations (
map,filter) without creating intermediate arrays - Infinite or unknown-length data: Generate values indefinitely or until a condition is met
- Early exit scenarios: Stop processing as soon as you find what you need (no wasted computation)
Example scenario: Processing a 10GB log file line-by-line—lazy lets you handle one line at a time without crashing.
When Eager Wins
Use eager evaluation (arrays) when:
- Data is small: The overhead of generators outweighs memory savings
- Reusing results: Arrays can be iterated multiple times; generators are one-time-use
- Random access needed: Arrays let you jump to any index; lazy sequences only move forward
- Simplicity matters: Arrays are familiar, easier to debug, and work with existing array methods
Example scenario: Filtering 50 items for display—just create the array. Simple, fast, reusable.
The Trade-Off
Lazy sequences reduce memory usage and enable elegant pipelines, but they add complexity: harder to debug, can't reuse the iterator, and require understanding generator mechanics. Eager is straightforward but can waste memory and computation if you don't need all results.
Key Takeaway: Choose lazy for large data, pipelines, or infinite sequences; choose eager for small, reusable collections where simplicity and random access matter.