Course contentsShow
← JavaScript
Lesson 871 of 2,72320. Array Iteration and TransformationFree lesson

Reduce Performance Considerations

Understand when reduce is efficient versus when simpler methods are clearer, and how to avoid creating excessive intermediate objects.

Reduce Performance Considerations

What you'll learn: When reduce is the right tool versus when simpler methods make your code faster and clearer.

The Efficiency Question

reduce is powerful, but it's not always the best choice. Think of it like using a Swiss Army knife to cut bread—it works, but a bread knife is simpler and faster.

When Reduce Is Efficient

reduce shines when you need to:

  • Compute a single value from an array (sum, product, single object)
  • Avoid multiple passes over the same data
  • Combine transformation and accumulation in one step
// Good: One pass, clear intent
const total = prices.reduce((sum, price) => sum + price, 0);

When Simpler Methods Win

Avoid reduce when a clearer alternative exists:

// Overcomplicated reduce
const doubled = nums.reduce((acc, n) => [...acc, n * 2], []);

// Better: Use map
const doubled = nums.map(n => n * 2);

The Hidden Cost: Intermediate Objects

Be careful creating new objects or arrays in each iteration:

// BAD: Creates a new array every iteration (O(n²) complexity!)
const result = arr.reduce((acc, item) => [...acc, item], []);

// GOOD: Mutate the accumulator (O(n) complexity)
const result = arr.reduce((acc, item) => {
  acc.push(item);
  return acc;
}, []);

That spread operator ...acc copies the entire array every time, turning a linear operation into a quadratic one.

Readability Matters

If your reduce callback spans more than a few lines or requires comments to understand, consider alternatives like map, filter, or a simple for loop.

Key Takeaway: Use reduce for actual reduction operations; prefer map and filter for transformations, and always avoid creating intermediate copies inside the accumulator loop.