jQuery Collection Iteration

JavaScript performance comparison

Revision 4 of this test case created by Joshua Piccari

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var $elems = $('*'),
      $elem;
};
</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
jQuery.fn.each()
$elems.each(function() {
  $elem = $(this);
});
pending…
for loop + .eq()
var i;
for (i = 0; i < $elems.length; i++) {
  $elem = $elems.eq(i);
}
pending…
for loop + $(.get())
var i;
for (i = 0; i < $elems.length; i++) {
  $elem = $($elems.get(i));
}
pending…
for loop + index
var i;
for (i = 0; i < $elems.length; i++) {
  $elem = $($elems[i]);
}
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:

2 comments

Curtis commented :

It might a better test to cache the length and reference that as a variable, since that is what jQuery's .each() does.

Joshua Piccari commented :

Actually, other perfs show that caching .length is a micro-optimization and in latest versions of Chrome is slower than not caching.

Add a comment