Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Comparing forEach() and reduce() for summing an array of numbers in JavaScript.
When summing arrays in JavaScript, both forEach() and reduce() are common approaches. This article compares their performance to help you choose the right method.
Since we can't demonstrate with truly massive arrays here, we'll simulate the performance impact by running the summing operation many times in a loop.
The Two Approaches
Here's how each method works for summing an array:
const arr = [1, 4, 4, 54, 56, 54, 2, 23, 6, 54, 65, 65];
// Using reduce() - functional approach
const reduceSum = arr => arr.reduce((acc, val) => acc + val);
// Using forEach() - imperative approach
const forEachSum = arr => {
let sum = 0;
arr.forEach(el => sum += el);
return sum;
};
// Test both methods
console.log("reduce() result:", reduceSum(arr));
console.log("forEach() result:", forEachSum(arr));
reduce() result: 383 forEach() result: 383
Performance Comparison
To measure performance differences, we'll run each method many times and compare execution time:
const arr = [1, 4, 4, 54, 56, 54, 2, 23, 6, 54, 65, 65];
const reduceSum = arr => arr.reduce((acc, val) => acc + val);
const forEachSum = arr => {
let sum = 0;
arr.forEach(el => sum += el);
return sum;
};
const iterations = 1000000;
// Time reduce()
console.time('reduce');
for(let i = 0; i < iterations; i++){
let sumReduce = reduceSum(arr);
}
console.timeEnd('reduce');
// Time forEach()
console.time('forEach');
for(let j = 0; j < iterations; j++){
let sumForEach = forEachSum(arr);
}
console.timeEnd('forEach');
reduce: 19.058ms forEach: 26.204ms
Performance Analysis
| Method | Approach | Performance | Readability |
|---|---|---|---|
reduce() |
Functional | Faster (~1.4x) | More concise |
forEach() |
Imperative | Slower | More explicit |
Why reduce() is Faster
reduce() is optimized specifically for accumulation operations like summing. It avoids external variable mutation and leverages internal optimizations in JavaScript engines.
forEach() requires maintaining an external sum variable and performs slightly more overhead per iteration.
Conclusion
For array summing operations, reduce() is both more performant and more idiomatic. The performance ratio is approximately 1:1.4, making reduce() the recommended choice for functional array operations.
