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];
}
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.
forEach loopIt is fast and designed for functional code. Now Its time to check the execution time for all three looping methods.
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.
map() is faster than forEach() Show activity on this post. The NodeList returned by querySelectorAll() is not an array. It happens to forEach() .
Here's a nice performance comparison. According to it Array.forEach
is slower than a native for
loop.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With