Array filter performance (v13)

Revision 13 of this benchmark created by Javier Lazaro on


Setup

var alpha = [852,759,386,675,851,789];
    
    
    var testElement = function(i) {
      return i > 500;
    }
    
    Array.prototype.filter2 = function(fun /*, thisArg */ ) {
      "use strict";
    
      if (this === void 0 || this === null)
        throw new TypeError();
    
      var t = Object(this);
      var len = t.length >>> 0;
      if (typeof fun !== "function")
        throw new TypeError();
    
      var res = [];
      var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
      for (var i = 0; i < len; i++) {
        if (i in t) {
          var val = t[i];
    
          // NOTE: Technically this should Object.defineProperty at
          //       the next index, as push can be affected by
          //       properties on Object.prototype and Array.prototype.
          //       But that method's new, and collisions should be
          //       rare, so use the more-compatible alternative.
          if (fun.call(thisArg, val, i, t))
            res.push(val);
        }
      }
    
      return res;
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Filter
var result = alpha.filter(testElement);
ready
Loop
function filter(a) {
  b = a.slice(0);
  for (var i = a.length - 1; i >= 0; i--) {
    if (!testElement(a[i]) !== true) b.splice(i, 1)
  }
  return b
}

var result = filter(alpha);
ready
bla
function filter(a) {
  b = a.slice(0);
  for (var i = a.length - 1; i >= 0; i--) {
    if (!testElement(a[i])) b.splice(i, 1)
  }
  return b
}

var result = filter(alpha);
ready
blubb
var result = alpha.filter2(testElement);
ready

Revisions

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