Speed of [].forEach.call(...?
Asked Answered
S

3

6

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];
}
Solicitude answered 23/2, 2010 at 10:47 Comment(2)
BTW for(var i=0, el; el = nodes[i]; i++) works as well :)Greengage
Do you have a specific performance case you are trying to solve? Otherwise which case you might to avoid premature optimization.Longmire
S
7

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

Spearman answered 23/2, 2010 at 10:49 Comment(1)
Cheers, thanks for the link. That's exactly what I was after. BTW, the jQuery.each speed is a bit surprising.Solicitude
G
4

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;
Gibby answered 13/12, 2012 at 13:2 Comment(3)
+1 Doing this once, then having someNodeList.forEach() looks much neater than either using .call() for every loop or using giant ES3-style 'for' loopsLongmire
But the ES5 spec says that "whether the forEach function can be applied successfully to a host object [like NodeList] is implementation-dependent." As far as a I know, Chrome and Firefox support forEach on host objects. I don't know about IE, Safari, Opera, etc.Gum
It is implementation dependant but this won't make any difference to the implementation on browsers that have done so (I haven't actually found any yet, will try Chrome though.)Gibby
C
1

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.

Confocal answered 13/4, 2011 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.