Royi Namir Royi Namir - 1 year ago 103
jQuery Question

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

I Can't understand why it is happening.

I read here that :

The first $.each constitutes a single function call to start the

The second $(foo.vals).each makes three function calls to start the

  • The first is to the $() which produces a new jQuery wrapper
    set (Not sure how many other function calls are made during this

  • Then the call to $().each.

  • And finally it makes the internal
    call to jQuery.each to start the iterator.

In your example, the difference would be negligible to say the least.
However, in a nested use scenario, you might find performance becoming
an issue.

Finally, Cody Lindley in jQuery Enlightenment does not recommend using
$.each for iterations greater than 1000 because of the function calls
involved. Use a normal for( var i = 0... loop.

So I tested it with this jsperf :

(task : find Tr's who has checked checkbox inside of them , and color that tr.)

This is the jsbin

But look at jsperf

against all expectations , the opposite is the true. ( chrome and FF and IE)

enter image description here

The one who uses
( which calls three methods is the fastest
and etc..

What is going on here?


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.

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

enter image description here