For vs ForEach vs For...of Performance
What you'll learn: How the three main iteration methods compare in speed and when those differences actually matter.
When you have multiple ways to loop through data, you might wonder: which is fastest? The answer depends on JavaScript engines, but general patterns exist.
The Performance Hierarchy
Traditional for loops are typically the fastest. They're bare-metal iteration with minimal overhead—just incrementing a counter and checking a condition:
const arr = [1, 2, 3, 4, 5];
// Fastest: direct index access, simple counter
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
forEach arrays method is slightly slower. It calls a function for each element, adding function call overhead:
// Moderate speed: function call per iteration
arr.forEach(item => {
console.log(item);
});
for...of loops fall somewhere between. They use the iterator protocol, which adds abstraction but cleaner syntax:
// Good speed: iterator protocol overhead
for (const item of arr) {
console.log(item);
}
When Performance Differences Matter
The reality: for most real-world code, these differences are negligible. Modern engines optimize heavily. You'll notice performance gaps only with:
- Huge datasets (tens of thousands of items or more)
- Tight loops running thousands of times per second
- Performance-critical applications (games, real-time processing)
For typical web development—UI rendering, API responses, user interactions—readability trumps micro-optimizations. Choose for...of for clarity unless profiling proves you need raw for loop speed.
Key Takeaway: Traditional for loops are fastest, for...of balances speed and readability, and forEach is slowest—but these differences rarely matter outside performance-critical scenarios. Optimize for clarity first, speed only when measured needs demand it.