Array reduce vs forEach (v15)

Revision 15 of this benchmark created by ChrisW on


Setup

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    Array.prototype.Aggregate = function(fn) {
      var current, length = this.length;
    
      if (length == 0) throw "Reduce of empty array with no initial value";
    
      current = this[0];
    
      for (var i = 1; i < length; ++i) {
        current = fn(current, this[i]);
      }
    
      return current;
    };

Teardown


    console.log(total);
  

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
var total = 0;
array.forEach(function(val) {
  total += val;
});
ready
reduce
var total = array.reduce(function(prev, curr) {
  return prev + curr;
});
ready
for
var total = 0;

for (var i = 0, n = array.length; i < n; ++i) {
  total += array[i];
}
ready
aggregate
var total = array.Aggregate(function(a, b) {
  return a + b
});
ready
while
var total = 0,
  i = 0,
  n = array.length;

while (i < n) {
  total += array[i];
  i += 1;
}
ready
son of while
var total = 0,
  i = 0,
  n = array.length;

while (i < n) {
  total += array[i++];
}
ready
evil eval
var total = eval(array.join("+"));
ready
for 2
var total = 0;

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

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

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

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

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

for (; i < n; total += array[i], i++) { }
ready
For(get) it and use tail recursion...
var total = (function sum(arr,tot) {
  return (arr.length===0) ? tot : sum(arr.slice(1),tot+arr[0]);
})(array,0);
ready
Tail Recursion - no slice
var total = (function sum(arr,tot,idx) {
  return (idx>=arr.length) ? tot : sum(arr,tot+arr[idx],++idx);
})(array,0,0);
ready
Tail recursion with global reference
var total = (function sum(tot,idx) {
  return (idx>=array.length) ? tot : sum(tot+array[idx],++idx);
})(0,0);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.