Filter vs for loop

JavaScript performance comparison

Revision 2 of this test case created by PhiLho

Info

Fix a bug! And trying to improve for loop

Preparation code

<script>
  var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
</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
Filter
var nlist = list.filter(function(n) {
  return n >= 5;
});
pending…
Initial for Loop
var nlist = [],
  i = 0,
  l = list.length;

for (; i < l; i++) {
  if (list[i] >= 5) {
    nlist.push(list[i]);
  }
}
pending…
Optimized for
// Marginally faster, gain is more important if more entries are matched
var nlist = [];
for (var i = 0, l = list.length; i < l; i++) {
  var v = list[i];
  if (v >= 5) {
    nlist.push(v);
  }
}
 
pending…
While loop
var nlist = [],
  i = 0,
  l = list.length;
while (i < l) {
  var v = list[i++];
  if (v >= 5) {
    nlist.push(v);
  }
}
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