jQuery.fn.each vs. jQuery.fn.quickEach

JavaScript performance comparison

Test case created by James Padolsey

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.

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()
a.each(function() {
 $(this);
});
pending…
.quickEach()
a.quickEach(function() {
 this; // jQuery object
});
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:

4 comments

Dave Stein commented :

This plug-in only works for arrays since objects don't have a .length function. This just wraps a function around a for loop.

Domenic Denicola commented :

This fails horribly when you try to capturing this in a variable for use in a closure that is not immediately executed, since this gets dynamically updated each loop-through:

http://jsfiddle.net/JNgvs/

Jeff Tucker commented :

@Domenic I think there was just a typo in the jsfiddle example. var $this = $(this); seems to work well.

http://jsfiddle.net/5RmaF/

Will Earp commented :

I like the idea of quickEach(), I am not totally sure how it works but I have found a problem with it. You cannot use another quickEach() inside a quickEach() loop.

When I get some time I will try and understand what it is doing and come up with a fix, but look forward to a solution if you think of one.

Add a comment