Iterator Memory Overhead vs Direct Array Access
What you'll learn: How iterators compare to traditional array indexing in terms of memory footprint and performance across different data sizes.
The Core Trade-off
When you use an iterator (via for-of, generators, or custom iterables), JavaScript creates an iterator object with internal state tracking. Each call to next() involves function overhead and object allocation. In contrast, direct array access with a traditional for loop uses a single index variable and directly reads memory locations—no intermediate objects, no function calls per iteration.
For small arrays (say, under 1,000 elements), the difference is usually negligible—modern engines optimize well. But as data size grows, the gap widens:
- Memory: Iterators hold state (current position, done flag, sometimes closures). Arrays accessed via index use only a primitive counter.
- Speed: Direct indexing is typically faster because it skips function call overhead and iterator protocol machinery.
When It Matters
- Tight loops over large arrays: If you're summing 10 million numbers,
for (let i = 0; i < arr.length; i++)will outperformfor (const num of arr)in raw speed. - Memory-constrained environments: Iterator objects add allocation pressure; direct access has almost zero overhead.
- Lazy sequences: Iterators shine when you don't need all data upfront. They consume memory only as you pull values—sometimes saving far more than they cost.
The Analogy
Think of direct array access as reading a numbered list directly: you flip to page 5, page 6, page 7. Iterators are like a librarian handing you one page at a time—convenient, but the librarian (iterator object) takes up space and time.
Key Takeaway: Iterators add small memory and speed overhead per iteration, but enable lazy evaluation. For hot paths over large in-memory arrays, direct indexing wins; for streams or infinite sequences, iterators are worth the cost.