[].forEach.call(...? 的速度

发布于 2024-08-23 00:26:04 字数 318 浏览 4 评论 0原文

我非常喜欢在 nodeLists 上使用 forEach 方法,如下所示:

var nodes = document.querySelectorAll(".foo");

[].forEach.call(nodes, function (item) {
    //do stuff with item
});

但我想知道,这样做是否比常规方式花费更长的时间? 例如

for(var i=0;i<nodes.length;i++){
    //do stuff with nodes[i];
}

I'm a big fan of using the forEach method on nodeLists like this:

var nodes = document.querySelectorAll(".foo");

[].forEach.call(nodes, function (item) {
    //do stuff with item
});

I was wondering though, does doing it that way take longer than the regular way?
e.g.

for(var i=0;i<nodes.length;i++){
    //do stuff with nodes[i];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冬天旳寂寞 2024-08-30 00:26:04

这是不错的性能比较。根据它,Array.forEach 比原生 for 循环慢。

Here's a nice performance comparison. According to it Array.forEach is slower than a native for loop.

奶气 2024-08-30 00:26:04

我知道这是一篇旧文章,但使用 forEach 方法也可以通过窃取数组原型来完成。

NodeList.prototype.forEach = Array.prototype.forEach;

I know it's an old post but using the forEach method can be done by stealing the Array prototype as well.

NodeList.prototype.forEach = Array.prototype.forEach;
南七夏 2024-08-30 00:26:04

这取决于浏览器。不要忘记 while(),它是 Firefox 4 上最快的。 这里有一个比较

另请记住,如果您支持不支持 forEach 的旧版浏览器,则需要添加 实现一个polyfill

It depends on the browser. And don't forget about while() which is the fastest on Firefox 4. Here's a comparison.

Also keep in mind that if you're supporting older browsers that don't support forEach, you need to add in the time it takes to implement a polyfill.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文