Splice vs filter (v4)

Revision 4 of this benchmark created on


Setup

Array.prototype.removeIf1 = 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;
    };
  Array.prototype.removeIf2 = function(callback) {
      var i = 0;
      while (i < this.length) {
          if (callback(this[i])) {
              this.splice(i, 1);
          }
          else {
              ++i;
          }
      }
  };

Test runner

Ready to run.

Testing in
TestOps/sec
ECMA-262 filter polyfill
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

array.removeIf1(function(item) {
    return item > 3;
});
ready
Filter
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

array.filter(function(item) {
    return item <= 3;
});
ready
Splice
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

array.removeIf2(function(item) {
    return item > 3;
});
ready

Revisions

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