jQuery.fn.each vs. jQuery.fn.quickEach vs. 'for loop' (v82)

Revision 82 of this benchmark created by Andy Harman on


Description

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 HTML

<script src="https://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>

Test runner

Ready to run.

Testing in
TestOps/sec
.each() + $(this)
a.each(function() {
 $(this).html(); // <- use jQuery to do something.
});
ready
.quickEach() + this
a.quickEach(function() {
 this.html(); // <- use jQuery to do something.
});
ready
.each() into wrapper
var $wrap = $(document.body); // <- single dummy element.
a.each(function() {
 $wrap[0] = this;
 $wrap.html(); // <- use jQuery to do something.
});
ready
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.
}
ready
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.
}
ready
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.
}
ready

Revisions

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