Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
// Given array 'arr'
var i = arr.length;
var sum = 0;
while (--i) sum += arr[i];
This will take on average 1.57 ms/run (measured over 1000 runs on an array of 100 random normal numbers), compared to 3.604 ms/run with the eval()
method above and 2.151 ms/run with a standard for(i,length,++) loop.
Methodology note: this test was run on a Google Apps Script server, so their javascript engines are pretty much the same as Chrome.
EDIT: --i
instead of i--
saves 0.12 ms each run (i-- is 1.7)
EDIT: Holy expletive, never mind this whole post. Use the reduce() method mentioned above, it's only 1 ms/run.