aarontgrogg Array.filter vs for-loop

JavaScript performance comparison

Revision 6 of this test case created

Info

Comparing the native Array.filter to a loop

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var sidekicks = [{
      name: "Robin",
      hero: "Batman"
    }, {
      name: "Supergirl",
      hero: "Superman"
    }, {
      name: "Oracle",
      hero: "Batman"
    }, {
      name: "Krypto",
      hero: "Superman"
    }],
      j, q;
    for (j = 0; j < 1000 - 4; j++) {
      sidekicks.push(sidekicks[j]);
    }
    q = {
      key: 'hero',
      value: 'Batman',
    };
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Array.filter
var batKicks = sidekicks.filter(function(el) {
  return (el.hero === "Batman");
});
pending…
for loop
var batKicks = [];

for (var i = 0; i < sidekicks.length; i++) {
  if (sidekicks[i].hero === "Batman") {
    batKicks.push(sidekicks[i]);
  }
}
pending…
for loop (w/v) with itemCache
var batKicks = [],
  sidekick;

for (var i = 0; i < sidekicks.length; i++) {
  sidekick = sidekicks[i];
  if (sidekick.hero === "Batman") {
    batKicks.push(sidekick);
  }
}
pending…
Query Loop
var batKicks = [];

for (var i = 0; i < sidekicks.length; i++) {
  if (sidekicks[i][q.key] === q.value) {
    batKicks.push(sidekicks[i]);
  }
}
pending…
Query Loop, cache key/value
var batKicks = [],
  key, value;

key = q.key;
value = q.value;
for (var i = 0; i < sidekicks.length; i++) {
  if (sidekicks[i][key] === value) {
    batKicks.push(sidekicks[i]);
  }
}
pending…
Query Loop with item cache
var batKicks = [],
  sidekick, key, value;

key = q.key;
value = q.value;
for (var i = 0; i < sidekicks.length; i++) {
  var sidekick = sidekicks[i];
  if (sidekick[key] === value) {
    batKicks.push(sidekick);
  }
}
pending…
Query Loop with length&item cache
var batKicks = [],
  sidekick,
  i, l, key, value;

key = q.key;
value = q.value;
for (i = 0, l = sidekicks.length; i < l; i++) {
  var sidekick = sidekicks[i];
  if (sidekick[key] === value) {
    batKicks.push(sidekick);
  }
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment