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

For-Of Loop Performance Compared to For Loop

Benchmark for-of iteration versus traditional for loops and understand modern engine optimizations.

For-Of Loop Performance Compared to For Loop

You'll learn: How for-of loops compare performance-wise to traditional for loops and when the difference actually matters.

The Performance Question

For years, developers have debated whether for-of loops are "slower" than traditional indexed for loops. The truth? Modern JavaScript engines have optimized for-of so much that in most real-world scenarios, the performance difference is negligible.

Why Traditional For Loops Were Faster

Traditional for loops access array elements by numeric index—a direct memory lookup:

const arr = [1, 2, 3, 4, 5];

// Direct indexed access
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

The for-of loop uses the iterator protocol, which historically added overhead:

// Uses Symbol.iterator under the hood
for (const value of arr) {
  console.log(value);
}

Modern Engine Optimizations

Today's JavaScript engines (V8, SpiderMonkey, JavaScriptCore) recognize common for-of patterns over arrays and optimize them to near-parity with indexed loops. The iterator protocol overhead is largely eliminated through inline caching and JIT compilation.

When the Difference Matters

Performance gaps only appear in:

  • Tight loops over millions of iterations with simple operations
  • Micro-benchmarks designed to amplify tiny differences
  • Hot paths in performance-critical code

For typical application code—UI updates, data processing, API handling—for-of is perfectly fast and far more readable.

The Pragmatic Choice

Choose for-of for clarity unless profiling reveals a bottleneck. Premature optimization based on theoretical performance differences is usually wasted effort.

Key Takeaway: Modern JavaScript engines have optimized for-of loops to perform nearly as fast as traditional for loops in practice; readability should guide your choice unless profiling proves otherwise.