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
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.
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:
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.