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

JavaScript performance comparison

Revision 107 of this test case created by Andy Harman


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 might be quickEach.

However for many scenarios, a simple for-loop can provide better performance. You just need to cache a reference to a jquery instance (like quickEach does internally). It does not fully replicate what the each method does - but in many cases it is good-enough.

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></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;

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
a.each(function() {
  $(this).css("background", "red"); // jQuery object
a.quickEach(function() {
  this.css("background", "red"); // jQuery object
native for loop
for (var i = 0, arr = a.length; i < arr; i++) {
  $(a[i]).css("background", "red");
native for loop with cached reference
//Reference to a single element jQuery collection.
var $x=$(0);

//Iterate thru list, substituting the current DOM element into
//out cached jQuery instance.
for (var i = 0; $x[0]=a[i]; i++) {
  $x.css("background", "red"); // jQuery object

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment