Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest JavaScript summation

What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run under SpiderMonkey.

Thinking very inside-the-box I have been using:

var count = 0;
for(var i = 0; i < array.length; i++)
{
    count = count + array[i];
}

I'm sure there is a better way then straight iteration.

like image 858
Josh K Avatar asked Sep 21 '10 16:09

Josh K


People also ask

Is there a sum () in JavaScript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.

How do you write a summation in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

What is sum += in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.

How do you find the greatest number in JavaScript?

Math. max() returns the largest number among the provided numbers. You can use Math. min() function to find the smallest among the numbers.


3 Answers

You should be able to use reduce.

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0); 

Source

And with arrow functions introduced in ES6, it's even simpler:

sum = array.reduce((pv, cv) => pv + cv, 0); 
like image 63
ChaosPandion Avatar answered Oct 29 '22 17:10

ChaosPandion


Improvements


Your looping structure could be made faster:


   var count = 0;    for(var i=0, n=array.length; i < n; i++)     {        count += array[i];     } 

This retrieves array.length once, rather than with each iteration. The optimization is made by caching the value.


If you really want to speed it up:


   var count=0;    for (var i=array.length; i--;) {      count+=array[i];    } 

This is equivalent to a while reverse loop. It caches the value and is compared to 0, thus faster iteration.

For a more complete comparison list, see my JSFiddle.
Note: array.reduce is horrible there, but in Firebug Console it is fastest.


Compare Structures

I started a JSPerf for array summations. It was quickly constructed and not guaranteed to be complete or accurate, but that's what edit is for :)

like image 40
vol7ron Avatar answered Oct 29 '22 15:10

vol7ron


While searching for the best method to sum an array, I wrote a performance test.

In Chrome, "reduce" seems to be vastly superior

I hope this helps

// Performance test, sum of an array
  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var result = 0;
// Eval
  console.time("eval");
  for(var i = 0; i < 10000; i++) eval("result = (" + array.join("+") + ")");
  console.timeEnd("eval");
// Loop
  console.time("loop");
  for(var i = 0; i < 10000; i++){
    result = 0;
    for(var j = 0; j < array.length; j++){
      result += parseInt(array[j]);
    }
  }
  console.timeEnd("loop");
// Reduce
  console.time("reduce");
  for(var i = 0; i < 10000; i++) result = array.reduce(function(pv, cv) { return pv + parseInt(cv); }, 0);
  console.timeEnd("reduce");
// While
  console.time("while");
  for(var i = 0; i < 10000; i++){
    j = array.length;
    result = 0;
    while(j--) result += array[i];
  }
  console.timeEnd("while");

eval: 5233.000ms

loop: 255.000ms

reduce: 70.000ms

while: 214.000ms

like image 35
Inkh Su Tesou Avatar answered Oct 29 '22 15:10

Inkh Su Tesou