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

JavaScript performance comparison

Revision 34 of this test case created by Vaibhav


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="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  var a = $('<div/>').append(Array(10000).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[0], i, jq) !== false);
    } catch (e) {
     delete jq[0];
     throw e;
    delete jq[0];
    return this;
   * jQuery each2 - v0.2 - 8/02/2010
   * http://benalman.com/projects/jquery-misc-plugins/
   * Inspired by James Padolsey's quickEach
   * http://gist.github.com/500145
   * Copyright (c) 2010 "Cowboy" Ben Alman
   * Dual licensed under the MIT and GPL licenses.
   * http://benalman.com/about/license/

  (function($) {
    // Create a placeholder jQuery object with a length of 1. The single item
    // is completely arbitrary and will be replaced.
    var jq = $([1]);
    $.fn.each2 = function( fn ) {
      var i = -1;
      while (
        // Set both the first element AND context property of the placeholder
        // jQuery object to the DOM element. When i has been incremented past the
        // end, this[++i] will return undefined and abort the while loop.
        ( jq.context = jq[0] = this[++i] )
        // Invoke the callback function in the context of the DOM element,
        // passing both the index and the placeholder jQuery object in. Like
        // .each, if the callback returns `false`, abort the while loop.
        && fn.call( jq[0], i, jq ) !== false
      ) {}
      // Return the initial jQuery object for chainability.
      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() {
a.quickEach(function() {
 this; // jQuery object
a.each2(function(i, elem) {
  this; // DOM element
  $(this); // 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