Computer >> Computer tutorials >  >> Programming >> Javascript

Comparing forEach() and reduce() for summing an array of numbers in JavaScript.


We are required to compare the time taken respectively by the ES6 functions forEach() and reduce() for summing a huge array of numbers.

As we can't have a huge array of numbers here, we will simulate the magnitude of array by performing the summing operation for large number of times (iterations)

Example

Let's write the code for this −

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 = 1000000000;
console.time('reduce');
for(let i = 0; i < iterations; i++){
   let sumReduce = reduceSum(arr);
};
console.timeEnd('reduce');
console.time('forEach');
for(let j = 0; j < iterations; j++){
   let sumForEach = forEachSum(arr);
};
console.timeEnd('forEach');

Output

Following is the output in the console −

reduce: 19.058s
forEach: 45.204s

So roughly, the ratio of time taken by Array.prototype.reduce() to the time taken by Array.prototype.forEach is  1 : 1.4