array-filter-while-vs-for

JavaScript performance comparison

Revision 2 of this test case created by jonschlinkert and last updated

Preparation code

<script src="https://rawgithub.com/lodash/lodash/2.4.1/dist/lodash.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  function filter1(arr, fn) {
    var copy = arr.slice(0);
    var len = arr.length - 1;
  
    for (var i = len; i >= 0; i--) {
      if (!fn(arr[i])) {
        copy.splice(i, 1);
      }
    }
    return copy
  }
  
  function filter2(arr, fn) {
    if (arr == null) {
      return [];
    }
  
    var len = arr.length;
    var res = [];
  
    for (var i = 0; i < len; i++) {
      var ele = arr[i];
  
      if (fn(ele, i, arr)) {
        res.push(ele);
      }
    }
    return res;
  }
  
  
  function filter3(arr, fn) {
    var res = [];
    var val;
  
    if (arr == null) {
      return res;
    }
  
    var len = arr.length;
    var i = -1;
  
    while (++i < len) {
      val = arr[i];
      if (fn(val, i, arr)) {
        res.push(val);
      }
    }
  
    return res;
  }
  
  // from https://github.com/juliangruber/array-filter
  
  function filter4(arr, fn, self) {
    if (arr.filter) return arr.filter(fn);
    if (void 0 === arr || null === arr) throw new TypeError;
    if ('function' != typeof fn) throw new TypeError;
    var ret = [];
    for (var i = 0; i < arr.length; i++) {
      if (!hasOwn.call(arr, i)) continue;
      var val = arr[i];
      if (fn.call(self, val, i, arr)) ret.push(val);
    }
    return ret;
  }
  
  var sparseArray = [];
  sparseArray[200] = 'a';
  
  var denseArray = [];
  for (var i = 0; i < 200; i++) {
    denseArray[i] = String.fromCharCode(Math.round(Math.random() * 95 + 33));
  }
  
  function callback(v) {
    return /\w+/.test(v);
  }

};
</script>

Preparation code output

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
filter4(denseArray, callback);
filter4(denseArray, callback);
pending…
filter4(sparseArray, callback);
filter4(sparseArray, callback);
pending…
filter1(sparseArray, callback);
filter1(sparseArray, callback);
pending…
filter1(denseArray, callback);
filter1(denseArray, callback);
pending…
filter2(sparseArray, callback);
filter2(sparseArray, callback);
pending…
filter2(sparseArray, callback);
filter2(sparseArray, callback);
pending…
filter3(sparseArray, callback);
filter3(sparseArray, callback);
pending…
filter3(denseArray, callback);
filter3(denseArray, callback);
pending…
native filter (dense)
denseArray.filter(callback);
pending…
native filter (sparse)
sparseArray.filter(callback);
pending…
lodash denseArray
_.filter(denseArray, callback);
pending…
lodash sparseArray
_.filter(sparseArray, callback);
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