JS reduce vs map vs foreach vs for loop

Which is the fastest method among reduce vs map vs foreach vs for loop?

JS reduce vs map vs foreach vs for loop

In my previous post Finding the sum of an array of numbers in JavaScript, I wrote about 4 different ways to find the sum of an array of numbers in JavaScript.

The 4 methods included the following javascript built in methods

  1. For loop
  2. Foreach loop
  3. Map
  4. Reduce

Initially I thought that reduce is the best method for doing so, as it looks clean, simple and also accurate.

var array = [5, 7, 6 ,3 ,2];
var sum = array.reduce((a,b) => a + b, 0);
console.log(sum); 

However after running a benchmark test of all the four methods using JSPerf, I found out that the reduce method which I thought of being the best turned out to be more than 90% slower as compared to the fastest method (for loop).

Here's what I did in the test

In the test, all the 4 methods were used to calculate the sum of the array [0, 1 ,2 ......, 100000]

I tested against a big array because, doing test on a small array will take almost the same time for all test cases.

I used the following code to initialize the array for all the test cases

function range(start, stop) {
    var array =[];
    for(var i=start;i<stop;i++){
        array.push(i)
    }
    return array
}

var array = range(0,100000)
var sum = 0;

Then I added four test cases of each of the 4 methods I mentioned.

Here's what the test results turned out to be

As you can conclude from the above image, the for loop function beat all the other functions by 90%.

For loop is the clear winner here.

The test doesn't end here

Because doing a single test is not enough to come into conclusions. I wanted to one more test.

This time I tested all the four methods to find product of an array.

Following is the result for our 2nd test

Yet again for loop is the clear winner. However, as you may have noticed, this time it's only 80% faster. Still way faster than the rest.

Map function is the slowest once again.

So, from the above two tests we can conclude that for loop is the best method to use when we want to calculate the sum or product of an array.

You can find links to my test cases here.

https://jsperf.com/js-product-thepoorcoder

https://jsperf.com/js-sum-thepoorcoder

You can also do your own tests using the above link.

Let me know in the comments how the test result looks like for a different datatype and test case for example string concetanation using all the four different methods.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe