我不明白为什么会这样。
我读了here那:
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.
所以我用这个 jsperf 测试了它:
(任务:找到选中复选框的 Tr,并为该 tr 着色。)
这是 jsbin
但是看看 jsperf
出乎意料,相反是真的。 ( Chrome 和 FF 和 IE)
使用 $().each
的(调用三个方法是最快的
等等。
这是怎么回事?
最佳答案
您的测试过于繁重,无法真正确定三个循环选项之间的实际差异。
如果你想测试循环,那么你需要尽可能多地从测试中删除不相关的工作。
就目前而言,您的测试包括:
- DOM 选择
- DOM遍历
- 元素突变
与循环本身相比,所有这些都是相当昂贵的操作。当删除多余的东西时,循环之间的区别更加明显。
http://jsperf.com/asdasda223/4
在 Firefox 和 Chrome 中,for
循环比其他循环快 100 倍以上。
关于javascript - $().each vs $.each vs for jQuery 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14808144/