Array function chains vs single loop (filter + reduce)

Benchmark created by tswistak on


Setup

var array = [];
  for (var i = 0; i < 1000000; i++) {
      array.push(i);
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Filter + Reduce
var sumOfEvens = array
    .filter(function(current) { return current % 2 === 0; })
    .reduce(function(previous, current) { return previous + current; }, 0);
ready
Reduce
var sumOfEvens = array.reduce(function(previous, current) { return current % 2 === 0 ? previous + current : previous; });
ready
ForEach
var sumOfEvens = 0;
array.forEach(function(current) {
    if (current % 2 === 0) {
        sumOfEvens += current;
    }
});
ready
For loop
var sumOfEvens = 0;
for (var i = 0; i < array.length; i++) {
    var current = array[i];
    if (current % 2 === 0) {
        sumOfEvens += current;
    }
}
ready

Revisions

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