Speed of [].forEach.call(…?

拥有回忆 提交于 2019-11-29 14:44:44

问题


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];
}

回答1:


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




回答2:


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;



回答3:


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.



来源:https://stackoverflow.com/questions/2317426/speed-of-foreach-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!