Array reduce vs forEach (v27)

Revision 27 of this benchmark created on


Setup

var array = [];
    for(var i = 0; i < 1000; i++)array[i] = Math.floor(Math.random() * 1000000);
    
    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;
    };

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
AggregateCacheRef
var total = array.AggregateCacheRef(function(a,b){ return a + b });
ready
reduce max
var max = array.reduce(function(prev, curr) {
  return prev > curr ? prev : curr;
});
ready
for max
var total = 0;

for(var i=0,n=array.length; i<n; ++i)
{
    var curr = array[i];
    max = curr > max ? curr : max;
}
ready

Revisions

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