$().each vs $.each vs for loop in jQuery? $().each vs $.each vs for loop in jQuery? jquery jquery

$().each vs $.each vs for loop in jQuery?


Your test is too heavy to really determine the actual difference between the three looping options.

If you want to test looping, then you need to do your best to remove as much non-related work from the test as possible.

As it stands, your test includes:

  • DOM selection
  • DOM traversal
  • element mutation

All of those are quite expensive operations compared to the loops themselves. When removing the extra stuff, the difference between the loops is much more visible.

http://jsperf.com/asdasda223/4

In both Firefox and Chrome, the for loop is well over 100x faster than the others.

enter image description here


Well

  • $.each() is a jQuery function being executed which will be used to iterate over your list, so the overhead should be the jQuery function as well as the overhead of calling for that function for every item in the list. In this case
  • $(thing).each() The idea behind this is that the $(thing) makes an jQuery instance and then you iterate over this instance (.each acts on that instance). In your case, because the instance you called it with is already a jQuery object, the overhead is minimal (are you an instance, oh yes you are).
  • for() In this case there is no overhead at all, except looking up the length of the list on each iteration.

Consider doing:

var l = g.length;for (var i=0;i<l;i++) {    // code;}

Depending on your HTML most of the time could very well be in the Sizzle Jquery parser finding your selector in the document.

Also note, I don't think your selector is the best, unless things have changed significantly recently jQuery selectors are evaluated right to left, consider limiting the scope of the selector by doing a .find() on everything beneath the first tag referenced by id as it will then be searching only a subset of the document.


Different approach to your "task" http://jsfiddle.net/ADMnj/17/

But i guess the performance issues are coming from that you dont state selector the in the right matter

#t tr input:checkbox:checked VS#t tr :checkbox:checked 

Tough the right way to check if a checkbox is checked would be to call it like this

#t tr input[checked="checked"]

W3.ORG's selector list see the E[foo]

And last but not least the fastest is also the one with the shortest code which might be the slight performance different you get from 3 lines vs 4 and 5 lines of code but cant prove this fact