jQuery.fn.each vs. jQuery.fn.quickEach vs. 'for loop'

JavaScript performance comparison

Revision 82 of this test case created by Andy Harman

Info

The quickEach method will pass a non-unique jQuery instance to the callback meaning that there will be no need to instantiate a fresh jQuery instance on each iteration. Most of the slow-down inherent in jQuery’s native iterator method (each) is the constant need to have access to jQuery’s methods, and so most developers see constructing multiple instances as no issue… A better approach would be quickEach ...

... or a simple loop.

The loop examples recreate the wrapper for each test run - but don't have the overhead of invoking a method-call for each iteration. Under IE9, quickEach is still marginally faster because it reuses a single "jq" wrapper forever.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
  var a = $('<div/>').append(Array(100).join('<a></a>')).find('a');
 
  jQuery.fn.quickEach = (function() {
   var jq = jQuery([1]);
   return function(c) {
    var i = -1,
        el, len = this.length;
    try {
     while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false);
    } catch (e) {
     delete jq[0];
     throw e;
    }
    delete jq[0];
    return this;
   };
  }());
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.each() + $(this)
a.each(function() {
 $(this).html(); // <- use jQuery to do something.
});
pending…
.quickEach() + this
a.quickEach(function() {
 this.html(); // <- use jQuery to do something.
});
pending…
.each() into wrapper
var $wrap = $(document.body); // <- single dummy element.
a.each(function() {
 $wrap[0] = this;
 $wrap.html(); // <- use jQuery to do something.
});
pending…
for loop 1 into wrapper
var $wrap = $(document.body); // <- single dummy element.
for(var i = 0; $wrap[0] = a[i]; i++){
    $wrap.html(); // <- use jQuery to do something.
}
pending…
while loop 1 into wrapper
var i=-1, len=a.length, $wrap = $(document.body); // <- single dummy element.
while (++i < len) {
 $wrap[0] = a[i];
 $wrap.html(); // <- use jQuery to do something.
}
pending…
while loop 2 into wrapper
var i=-1, $wrap = $(document.body); // <- single dummy element.
while ($wrap[0]=a[++i]) {
 $wrap.html(); // <- use jQuery to do something.
}
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