Memory Benefits of Lazy Sequences
You'll learn: How lazy sequences save memory by generating values on-demand instead of storing entire collections in memory at once.
The Memory Problem with Eager Approaches
When you process data eagerly, every intermediate result gets stored in memory. If you have a million numbers and apply three transformations, you create three million-element arrays—one for each step. That's a lot of memory!
// Eager approach - creates full arrays in memory
const numbers = Array.from({ length: 1_000_000 }, (_, i) => i);
const doubled = numbers.map(n => n * 2); // 1 million items in memory
const filtered = doubled.filter(n => n > 100); // Another million items
const first10 = filtered.slice(0, 10); // Finally get 10 items
All those intermediate arrays stick around until garbage collection kicks in.
How Lazy Sequences Save Memory
Lazy sequences using generators compute values one at a time, only when needed. No intermediate arrays are created. It's like a factory assembly line where parts are made just-in-time rather than stockpiling millions of pieces at each station.
function* lazyMap(iterable, fn) {
for (const item of iterable) {
yield fn(item);
}
}
function* lazyFilter(iterable, predicate) {
for (const item of iterable) {
if (predicate(item)) yield item;
}
}
// Lazy approach - only 10 values ever exist in memory
const pipeline = lazyFilter(
lazyMap(function*() { let i = 0; while(true) yield i++; }(), n => n * 2),
n => n > 100
);
const first10 = Array.from({ length: 10 }, () => pipeline.next().value);
With infinite sequences, eager approaches would crash—lazy sequences handle them gracefully because they never try to materialize the entire collection.
Key Takeaway: Lazy sequences trade memory for computation—they use constant memory regardless of sequence size, computing values on-demand instead of storing massive intermediate collections.