Array reduce vs forEach (v21)

Revision 21 of this benchmark created 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];
      var i = 1;
      while ( i < length) {
        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 = -1, n = array.length; ++i < n;) {
  total += array[i];
}
ready
aggregate
var total = array.Aggregate(function(a, b) {
  return a + b
});
ready
for in
var total = 0;

for (var i in array) {
  total += array[i];
}
ready

Revisions

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