Test case details

Preparation Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- the plugin --> <script> $.fn.extend({       /*       * 4-10 times faster .each replacement       * use it carefully, as it overrides jQuery context of element on each iteration       */       each2 : function (c) {         var j = $([0]), i = -1, l = this.length;         while (           ++i < l           && (j.context = j[0] = this[i])           && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object         );         return this;       }     }); </script> <script>   // Create a whole bunch of elements for iteration.   var elems = $('<div/>').append(Array(1000).join('<span/>')).children(); </script>

Test cases

Test #1

elems.each2(function(i, jq) {  jq; // Use at will!  jq; // No performance penalty.  jq; // No performance penalty. });

Test #2

elems.each(function(i, elem) {  var jq = $(this); // This is the best we can do here.  jq; // No performance penalty.  jq; // No performance penalty.  jq; // No performance penalty. });

Test #3

elems.each(function(i, elem) {  $(this); // Really inefficient code, you know,  $(this); // like you see all over the web... });

Test #4

elems.each(function(i, elem) {  $(this); // Really inefficient code, you know,  $(this); // like you see all over the web...  $(this); // Etc...  $(this); // Etc... });

Test #5

elems.each(function(i, elem) {  for (var i = 0; i < 10; i++) {   $(this); // Let's see the cost of doing $(this) 10x.  } });

Test #6

elems.each2(function(i, jq) {  // This should give some sense of how disproportionate the  // $(this) savings are compared to actual DOM manipulations.  jq.addClass('foo'); });