Splice vs filter (v9)

Revision 9 of this benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

Array.prototype.removeIf1 = function(expression) {
    var res = [];
    for (var idx = 0; idx < this.length; idx++) {
      var currentItem = this[idx];
      if (!expression(currentItem)) {
        res.push(currentItem);
      }
    }
    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
Push
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
Splice inline
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0,
  l = array.length;
while (i < l) {
  if (array[i] < 3) {
    array.splice(i, 1);
    l = array.length
  } else {
    ++i;
  }
}
ready

Revisions

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