Course contentsShow
← JavaScript
Lesson 2055 of 2,72342. Iteration Protocols Deep DiveFree lesson

When Lazy Evaluation Wins

Comparing memory and performance: scenarios where lazy iterators outperform eager array methods.

When Lazy Evaluation Wins

You'll learn: When and why lazy iterators outperform eager array methods in terms of memory and performance.

The Core Idea

Lazy evaluation shines in three key scenarios: when working with large or infinite datasets, when you don't need all results, or when each operation is computationally expensive. Unlike eager array methods that process everything upfront, lazy iterators compute values only as needed.

Memory Advantage

Eager array methods create intermediate arrays at each step. Chain three operations on a million-item array? You've created three temporary million-item arrays in memory. Lazy iterators hold minimal state—just enough to know where they are in the sequence.

// Eager: creates 3 intermediate arrays
const eagerResult = hugeArray
  .map(x => x * 2)      // Full array copy
  .filter(x => x > 100) // Another full array
  .slice(0, 10);        // Finally take 10

// Lazy: processes only what's needed
function* lazyPipeline(iterable) {
  for (const x of iterable) {
    const doubled = x * 2;
    if (doubled > 100) yield doubled;
  }
}
const lazyResult = take(lazyPipeline(hugeArray), 10);

When Lazy Wins

Early termination: Need the first 5 matches from a billion records? Lazy iterators stop immediately. Eager methods process everything first.

Infinite sequences: Eager methods can't handle infinite ranges or streams. Lazy iterators thrive here.

Expensive operations: If each transformation is costly (API calls, heavy computation), lazy evaluation only pays that cost for items you actually consume.

Memory-constrained environments: Processing large files or streams? Lazy evaluation keeps memory usage constant regardless of input size.

Key Takeaway: Lazy evaluation wins when you need a subset of results, work with large/infinite datasets, or want to avoid creating intermediate collections—offering constant memory usage and the ability to short-circuit expensive computations.