Skip to content

Instantly share code, notes, and snippets.

@uhop
Created October 21, 2010 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhop/638003 to your computer and use it in GitHub Desktop.
Save uhop/638003 to your computer and use it in GitHub Desktop.
Iterating over array
// Benchmarking summation of array
var a = [];
for(var i = 0; i < 100; ++i) a.push(Math.random());
this.group(
"Iterations",
function classic(){
for(var sum = 0, i = 0, l = a.length; i < l; ++i){ sum += a[i]; }
},
function short(){
for(var sum = 0, i = 0, l = a.length; i < l; sum += a[i++]);
},
function forEach(){ var sum = 0; a.forEach(function(x){ sum += x; }); },
function reduce(){ var sum = a.reduce(function(a, b){ return a + b; }, 0); },
function reduceRight(){ var sum = a.reduceRight(function(a, b){ return a + b; }, 0); }
);
@uhop
Copy link
Author

uhop commented Oct 21, 2010

Benchmark it with http://www.perfjs.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment