jQuery grep vs each (v7)

Revision 7 of this benchmark created on


Description

The target is to get all objects with name: "abc" into a single array. There are two search operations, one with a small set and one with a large set, that is basically 1000 times greater than the small set.

There is a interesting difference between the $.grep and the for-loop example, as the more items they have to compare, the closer they get in terms of performance (from 60% slower to around 20% slower)

Preparation HTML

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

<script>
  var arrToSearchThrough_large = [];
  var arrToSearchThrough_small = [{
   name: "7",
   res: "f"
  },
  {
   name: "6",
   res: "f"
  },
  {
   name: "4",
   res: "f"
  },
  {
   val: "9",
   res: "f"
  },
  {
   name: "112",
   res: "f"
  },
  {
   val: "abc",
   res: "f 1"
  },
  {
   val: "ddd",
   res: "f"
  },
  {
   name: "fff",
   res: "f"
  },
  {
   name: "abc",
   res: "f 2"
  },
  {
   name: "f",
   res: "f"
  },
  {
   name: "abc",
   res: "f 3"
  }];
  for (i = 0; i < 1000; i++)
  arrToSearchThrough_large.push(arrToSearchThrough_small);
  var arrResults = [];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
1 jQuery.grep small
arrResults = $.grep(arrToSearchThrough_small, function(n, i) {
 return (n.name == "abc");
});
ready
2 jQuery.each small
$(arrToSearchThrough_small).each(function() {
 if (this.name == "abc") arrResults.push(this);
});
ready
3 for-loop small
for (i = 0; i < arrToSearchThrough_small.length; i++) {
 if (arrToSearchThrough_small[i].name == "abc") arrResults.push(arrToSearchThrough_small[i]);
}
ready
6 jQuery.grep large
arrResults = $.grep(arrToSearchThrough_large, function(n, i) {
 return (n.name == "abc");
});
ready
7 jQuery.each large
$(arrToSearchThrough_large).each(function() {
 if (this.name == "abc") arrResults.push(this);
});
ready
8 for-loop large
for (i = 0; i < arrToSearchThrough_large.length; i++) {
 if (arrToSearchThrough_large[i].name == "abc") arrResults.push(arrToSearchThrough_large[i]);
}
ready
4 jQuery.filter small
arrResults = $(arrToSearchThrough_small).filter(function(index) {
 return (this.name == "abc");
});
ready
9 jQuery.filter large
arrResults = $(arrToSearchThrough_large).filter(function(index) {
 return (this.name == "abc");
});
ready
5 jQuery.each #2 small
$.each(arrToSearchThrough_small, function() {
 if (this.name == "abc") arrResults.push(this);
});
ready
10 jQuery.each #2 large
$.each(arrToSearchThrough_large, function() {
 if (this.name == "abc") arrResults.push(this);
});
ready
lodash
_.filter(arrToSearchThrough_large,
function(elto) { return elto.name === "abc"  });
ready

Revisions

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