Array reduce vs forEach (v46)

Revision 46 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];
    
        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;
function sum(val) {
  total += val;
}
array.forEach(sum);
ready
reduce
function sum(prev, curr) {
  return prev + curr;
}
var total = array.reduce(sum);
ready
for
var total = 0;

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

Revisions

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