Iterator Chain Performance: Composition Cost
You'll learn how chaining multiple iterator transformations compares to single-pass array methods in terms of performance overhead.
The Composition Problem
When you chain lazy iterator operations—like .map(), .filter(), .take()—each transformation wraps the previous iterator in another layer. Every element that flows through the chain must pass through multiple iterator protocol calls (next(), value, done checks).
Think of it like a factory assembly line where each station adds a layer of paperwork. A three-stage iterator chain requires three separate next() calls per element, creating intermediate iterator objects at each stage. While lazy evaluation avoids processing all elements upfront, each processed element pays a composition cost.
Single-Pass Arrays vs Iterator Chains
Array methods like .map().filter() create intermediate arrays, but modern JavaScript engines optimize these heavily. The iteration itself is fast—just incrementing an index and direct memory access.
Iterator chains avoid intermediate arrays but introduce:
- Function call overhead per stage
- Iterator state management per layer
- Additional object allocations for each wrapper
For short chains on small datasets, arrays often win due to CPU cache locality and engine optimizations. For long pipelines or partial consumption (like taking the first 10 from millions), lazy iterators shine—you never touch most elements.
The Trade-Off
If you're processing every element through a 2-3 stage pipeline, array methods may actually be faster. If you're searching for early matches or working with infinite sequences, iterator chains win by avoiding unnecessary work entirely.
Key Takeaway: Iterator chains trade per-element overhead for the ability to short-circuit—profile your specific use case, as composition cost can outweigh laziness benefits on small, fully-consumed datasets.