array filter: jQuery.each vs jQuery.grep vs for loop

JavaScript performance comparison

Revision 14 of this test case created by

Preparation code

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

      
<script>
Benchmark.prototype.setup = function() {
  var largeArray = new Array(10000);
  for (var tmpix = 0; tmpix < 10000; tmpix++) {
    largeArray[tmpix] = {
      a: Math.floor(Math.random() * 10000),
      b: 10000 - tmpix,
      c: "element" + tmpix
    }
  }

};
</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
jQuery.grep
var result = jQuery.grep(largeArray, function(e) {
  return (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999");
});
pending…
Array.filter
var result = largeArray.filter(function(e) {
  return (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999");
});
pending…
jQuery.each
var result = [];

jQuery.each(largeArray, function(index, e) {
  if (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999") {
    result.push(e);
  }
});
pending…
Array.forEach
var result = [];

largeArray.forEach(function(e) {
  if (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999") {
    result.push(e);
  }
});
pending…
for loop
var result = [],
  element,
  i;

for (i = 0; i < largeArray.length; i++) {
  e = largeArray[i];
  if (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999") {
    result.push(e);
  }
}
pending…
grep by for loop and callback
var result = [];

function myGrep(a, fn) {
  var i, l = a.length,
    e, r = [];
  for (i = 0; i < l; i++) {
    e = a[i];
    if (fn(e)) {
      r.push(e)
    }
  }
  return r;
}

function fn(e) {
  return (e.a < 10 || e.a > 9990 || e.b < 10 || e.b > 9990 || e.c > "element999")
}

myGrep(largeArray, fn);
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