arr-map-filter-reduce (v4)

Revision 4 of this benchmark created by G. Lathoud on


Description

native vs 3 loops vs. 1 loop.

Setup

var n = 10000,
      arr = new Array(n)
      drop = 0.1 // Proportion of numbers to drop
      ;
    
    // Deterministic pseudo-random numbers to make sure
    // arr is always generated the same way.
    // http://stackoverflow.com/questions/521295/javascript-random-seeds
    var seed = 1;
    
    function random() {
      var x = Math.sin(seed++) * 10000;
      return x - Math.floor(x);
    }
    
    for (var i = n; i--;)
      arr[i] = {
        p: random() < drop ? null : i
      };

Test runner

Ready to run.

Testing in
TestOps/sec
3 loops
// .map(".p")
var tmp_1 = new Array(n);
for (var i = 0; i < n; i++)
  tmp_1[i] = arr[i].p;

// .filter("!=null")
var tmp_2 = [];
for (var i = 0; i < n; i++) {
  var v = tmp_1[i];
  if (v != null)
    tmp_2.push(v);
}

// .reduce("+")
var sum = 0;
for (var n2 = tmp_2.length, i = 0; i < n2; i++)
  sum = sum + tmp_2[i];
ready
1 loop
  var sum = 0,
    n = arr.length;
  for (var i = 0; i < n; i++) {
    var v = arr[i];
    v = v.p; // .map(".p")
    if (v != null) // .filter("!=null")
      sum = sum + v; // .reduce("+")
  }
ready
native
var sum = arr.map(function(x) { return x.p; })
  .filter(function(x) { return x != null; })
  .reduce(function(a, b) { return a + b; })
;
ready

Revisions

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

  • Revision 4: published by G. Lathoud on