Array reduce vs forEach (v10)

Revision 10 of this benchmark created by Erwin 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;
    };
    
    Array.prototype.AggregateCacheRef = function(fn) {
      var current, a = this,
        length = a.length;
    
      if (length == 0) throw "Reduce of empty array with no initial value";
    
      current = a[0];
    
      for (var i = 1; i < length; ++i) {
        current = fn(current, a[i]);
      }
    
      return current;
    };
    
    sumArray = (function() {
      // Use one adding function rather than create a new one each
      // time sumArray is called.
      function add(a, b) {
        return a + b;
      }
      return function(arr) {
        return arr.reduce(add);
      };
    }());

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
for (reverse)
var total = 0;

for (var n = array.length; n >= 0; n--) {
  total += array[n];
}
ready
aggregate
var total = array.Aggregate(function(a, b) {
  return a + b
});
ready
AggregateCacheRef
var total = array.AggregateCacheRef(function(a, b) {
  return a + b
});
ready
Test 6
var total = 0;
var length = array.length;

while (length--) total += array[length];
ready
Reduce w/ predefined addition function
var total = sumArray(array);
ready

Revisions

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