javascript - $().each vs $.each vs for jQuery 中的循环?

标签 javascript jquery each

我不明白为什么会这样。

我读了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)

enter image description here

使用 $().each 的(调用三个方法是最快的 等等。

这是怎么回事?

最佳答案

您的测试过于繁重,无法真正确定三个循环选项之间的实际差异。

如果你想测试循环,那么你需要尽可能多地从测试中删除不相关的工作。

就目前而言,您的测试包括:

  • DOM 选择
  • DOM遍历
  • 元素突变

与循环本身相比,所有这些都是相当昂贵的操作。当删除多余的东西时,循环之间的区别更加明显。

http://jsperf.com/asdasda223/4

在 Firefox 和 Chrome 中,for 循环比其他循环快 100 倍以上。

enter image description here

关于javascript - $().each vs $.each vs for jQuery 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14808144/

相关文章:

javascript - 如何使用 jquery 加载和验证表单?

javascript - 如何避免这个很长的 if else 语句

javascript - 在 Javascript/jQuery 中播放完声音后刷新页面

jquery - 动态追加数据到div

jquery - 如何用jquery一一显示和隐藏每个div

javascript - 在 Firefox 中检测页面加载完成事件

javascript - 为什么单选按钮的文本无法显示?

javascript - Chrome 平滑滚动和 requestAnimationFrame?

jquery - 如何切换鼠标的垂直和水平滚动?

javascript - 对于列表中包含带文本的范围的每个 li,从该 li 中删除另一个范围