$()。每个vs $ .each vs for jQuery中的循环? [英] $().each vs $.each vs for loop in jQuery?
问题描述
我无法理解为什么会这样。
我读过
在Firefox和Chrome中, for
循环比其他循环快100多倍。
I Can't understand why it is happening.
I read here that :
The first $.each constitutes a single function call to start the iterator.
The second $(foo.vals).each makes three function calls to start the iterator.
- The first is to the $() which produces a new jQuery wrapper set (Not sure how many other function calls are made during this process).
- 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)
The one who uses $().each
( 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.
http://jsperf.com/asdasda223/4
In both Firefox and Chrome, the for
loop is well over 100x faster than the others.
这篇关于$()。每个vs $ .each vs for jQuery中的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!