Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of [].forEach.call(...?

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];
}
like image 263
Yansky Avatar asked Feb 23 '10 10:02

Yansky


People also ask

Is forEach faster than for of?

As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.

Is forEach loop slow?

forEach loopIt is fast and designed for functional code. Now Its time to check the execution time for all three looping methods.

Why is forEach slow?

ForEach is 96% slower than for loop. Thanks in advance. It's probably because forEach requires a function call for each element. That doesn't quite explain why it's 96% faster though, you'd expect 50% since you make 1 function call instead of 2 for each element.

What is faster forEach or map?

map() is faster than forEach() Show activity on this post. The NodeList returned by querySelectorAll() is not an array. It happens to forEach() .


2 Answers

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

like image 168
Darin Dimitrov Avatar answered Sep 19 '22 20:09

Darin Dimitrov


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;
like image 41
Dave Mackintosh Avatar answered Sep 21 '22 20:09

Dave Mackintosh