Array sum: Comparing recursion vs for loop vs ES6 methods in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have an array with a huge number of Number entries and are required to compare the time recursion takes versus the time a simple loop takes versus the time ES6 function takes in summing all the entries of the array i.e. recursion vs for loop vs ES6 function.

Here, to simulate a large array we will iterate over a relatively smaller array for a large number of times (of the order of 10000000). Our main aim is just to have a rough ratio of the time each method takes in summing the array.

Part 1: Recursive Approach

const recursiveSum = (arr, len = 0, sum = 0) => {
   if(len < arr.length){
      return recursiveSum(arr, len+1, sum + arr[len]);
   };
   return sum;
};

Part 2: Looping Approach

const loopingSum = arr => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      sum += arr[i];
   };
   return sum;
};

Part 3: ES6 Approach

const ES6Sum = arr => arr.reduce((acc, val) => acc+val);

Now let’s compare the performance of these three functions with the help of console methods time() and timeEnd() −

Example

const ITERATIONS = 100000000;
const arr = [12, 65, 87, 2, 23, 87, 4, 66, 34, 89, 89, 32, 4];
const recursiveSum = (arr, len = 0, sum = 0) => {
   if(len < arr.length){
      return recursiveSum(arr, len+1, sum + arr[len]);
   };
   return sum;
};
const loopingSum = arr => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      sum += arr[i];
   };
   return sum;
};
const ES6Sum = arr => arr.reduce((acc, val) => acc+val);
console.time('recursive approach');
for(let k = 0; k < ITERATIONS; k++){
   recursiveSum(arr);
};
console.timeEnd('recursive approach');
console.time('looping approach');
for(let l = 0; l < ITERATIONS; l++){
   loopingSum(arr);
};
console.timeEnd('looping approach');
console.time('ES6 approach');
for(let m = 0; m < ITERATIONS; m++){
   loopingSum(arr);
};
console.timeEnd('ES6 approach');

Now let’s take a look at the possible console output −

Note − This is just a possible console output, as the performance of any piece of code depends heavily upon the system. But the ratio of time taken by these three functions will more or less be same across all systems.

recursive approach: 13.774s
looping approach: 3.138s
ES6 approach: 2.493s

So, here we can see on a particular machine, the times taken by three approaches for a large number of iterations. This shows that for smaller and basic calculations over an array, the ES6 functions are more efficient and performant than any other approach.

Note − For better results, avoid testing this code in online IDEs.

raja
Updated on 28-Aug-2020 13:45:18

Advertisements