Array function chains vs single loop (filter + reduce)

JavaScript performance comparison

Test case created by tswistak

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var array = [];
  for (var i = 0; i < 1000000; i++) {
      array.push(i);
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

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

Compare results of other browsers

Revisions

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

0 Comments