Advertisement
Advanced JavaScript, Iterators & Generators

What's the performance and memory advantage of a generator-based lazy pipeline over building intermediate arrays with map/filter?

Short answer

Chaining array methods like map().filter() creates a full new intermediate array at each step, even if you only need a few results.

Save JavaScript mock interview
Advertisement
AModel answer
Chaining array methods like map().filter() creates a full new intermediate array at each step, even if you only need a few results. A generator-based pipeline processes and yields one item at a time end-to-end, avoiding intermediate arrays entirely — especially valuable for large or infinite sequences where you only consume a subset.
function* map(iter, fn) { for (const x of iter) yield fn(x); }
function* filter(iter, pred) { for (const x of iter) if (pred(x)) yield x; }
function* take(iter, n) { let i = 0; for (const x of iter) { if (i++ >= n) return; yield x; } }

const result = [...take(filter(map(hugeSource, x => x * 2), x => x > 100), 5)];
Real-world example
Processing the first 5 matching results from a huge or infinite dataset without transforming the entire dataset first.
Likely follow-ups
  • At what dataset size does this lazy approach actually start to matter for performance?
Related topics