Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing jQuery each with for

I've been using $.each to do iterations for a while now, but I keep on hearing people say to use native JS for to do loops. I'm very concerned about performance but I am not sure if it's always possible to replace $.each with for in a meaningful way.

So my questions are, is it possible to always replace $.each with for, and if not what's the rule of thumb for when it can be done and when it cannot.

I have an each like this:

 $this.find("div.class").each(function (){
  var $thisparent = $(this).parent();

  if (condition) {          
   $(this).prepend($thisparent.text());
  }

  if (condition2) {          
   $(this).prepend($thisparent.text());
  }

 });
like image 785
Mark Avatar asked Aug 31 '09 23:08

Mark


2 Answers

This is what jQuery does with .each, basically:

$.fn.each = function(callback) {
    var i, length = this.length;
    for(i = 0; i < length; ++i) {
        callback.call(this[i]);
    }
};

So it's not hard to substitute your anonymous function's 'contents' with the callback.call call. Just be sure to replace this with a temporary with the jQuery object.

Converting your supplied code:

var foo = $this.find("div.class"),
    fooLength = foo.length,
    i,
    $thisparent;

for (i = 0; i < fooLength; ++i) {
    $thisparent = $(foo[i]).parent();

    if (condition) {          
        $(foo[i]).prepend($thisparent.text());
    }

    if (condition2) {          
        $(foo[i]).prepend($thisparent.text());
    }
}

For additional (potential) speed, cache foo[i] into a temporary. too, and assign $thisparent only when needed. If condition and condition2 are mutually exclusive, use a single if (condition || condition2).

like image 89
strager Avatar answered Oct 08 '22 07:10

strager


Someone compared the performance of for and $.each:

http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html

like image 37
karim79 Avatar answered Oct 08 '22 09:10

karim79