kvzbpa
Last Updated: September 14, 2017
·
548.7K
· afshinm
Add92525ab635b5119671269d24c1449

Don't use Array.forEach, use for() instead

Array.ForEach is about 95% slower than for() in for each for Arrays in JavaScript.

So, don't use:

arr.forEach(function (item) {
  someFn(item);
})

Use:

for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}

See this performance test online: http://jsperf.com/fast-array-foreach

Say Thanks
Respond

37 Responses
Add your response

2110

In first example you can write something like this:

arr.forEach(someFn);

It's really useful.
In some cases you'll realy need to use forEach method. For example, if you need a closure for your loop.

elements.forEach(function(element){
  var attribute = element.getAttribute('data-attr');
  element.onclick = function(){
    alert(attribute);
  };
});
over 1 year ago ·
2112
Add92525ab635b5119671269d24c1449

@avenger7x Sure, yes. I forgot to mention when we need to use forEach but in some cases that I saw in applications, it uses incorrectly and only because it's easy-to-use.

over 1 year ago ·
2116
81829def637962204635704c091036ea

for loops are really annoying when you're trying to build something complex, maintainability becomes harder, I think that there is a third solution http://mlb.tl/LIFL which is faster than forEach and still keeps a nice FP & OO coding-style.

Otherwise I agree that for small scripts, a good old for loop can be accurate.

over 1 year ago ·
2119
Add92525ab635b5119671269d24c1449

@mlb Hey Thanks, good alternative solution.

over 1 year ago ·
5778

Hello!
This is faster:
Array.prototype.forEach2=function(a){
var l=this.length;
for(var i=0;i<l;i++)a(this[i],i)
}
http://jsperf.com/sdngjkn

over 1 year ago ·
6538
388d93e

One other reason not to use Array.forEach is that it is not supported by IE8.

over 1 year ago ·
13714
3db39d82aa8ef1ed48d4864fa8914613

lol. Since when IE8 is supposed to rule our choices ?
The fact that IE8 doesn't support Array.forEach really means this bowser is deep shit, that's all ! ;)

over 1 year ago ·
14871
0 5p24ii3mi4rr mb4fqfbiecyixurke94fn4bie3aqszi723zdvpqshvhla2x17cqkka62fxg1lpp

Micro premature optimization is the root of so many evils. The rule is don't use it in a tight loop. Anywhere else, it will never matter. DOM maintenance is where you should optimize.

over 1 year ago ·
17942
4f7e8e1c71f327206af087394ba0ce30

One other reason to use Array.forEach is that it is not supported by IE8. ;-)

over 1 year ago ·
19298
None

JSPerf is a double-edged sword, you really need to start thinking about what it does and how it can return confusing results. Furthermore, 95% slower is practically NOTHING in terms of JS performances. What you need to focus on is Draw counts (if you are working the canvas) or plain DOM updates. Check out this great speak on micro-optimizations: https://www.youtube.com/watch?v=65-RbBwZQdU

over 1 year ago ·
20316
None

@william_malo, your test is misleading. Your vanilla javascript for loop was not actually calling the function, but merely running the guts of the function within the loop. Here is a more accurate test: http://jsperf.com/sdngjkn/19

over 1 year ago ·
20907
36b0338fc781b0572198e33531d2bc17

In your test and in ntg's, forEach was the fastest in Firefox 38 on 64-bit Linux (Slackware).

over 1 year ago ·
23831
None

for() loop runs in sync mode, it is too bad for a js application, if you are programming a js app, you'd better use Array.forEach, it runs in async mode, else you won'd go far.

over 1 year ago ·
26560
None
over 1 year ago ·
27039
000f45b685d4d6ff1a171676512c382e

There is a difference between for and forEach. for will local reassign variable for every run, while forEach will create new variable. Example:

var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
  var element = links[i];
  element.addEventListener('click', function () {
    alert(element.innerText); // you think it will be element you clicked on? It will be last element in array
  });
}
over 1 year ago ·
27355
Img 20151108 wa0019

The main reason for using for loops over Array.forEach is that you cannot break the latter. Other than that, I prefer the Array.forEach semantics. If performance degradation is really noticeable I will take into account your suggestion. Thank you.

over 1 year ago ·
27419
Poyothumb

Note that this is only for ES5 in a browser. If you've got ES6 then you'll want to use for ( X of arr ) { ... }.

over 1 year ago ·
27469

Don't forget to weigh performance against legibility/maintainability. As juanmendes said, premature optimization can yield problems.

over 1 year ago ·
27609

Personal opinion, here, but I think there is a larger issue being overlooked here.

The purpose of either for() or .forEach() is presumably to actually do something with each of the array elements. Simply comparing the two method's speed, divorced from actually doing anything inside their loops is a rather meaningless comparison. The work being done inside the loop of each method is going to dwarf the execution speed of the looping mechanism itself, almost to the point of irrelevance.

By the time you add a simple database lookup, and a printf(), 99.9% of the time is going to be spent on the work, and 0.1% of the time is consumed by the actual looping mechanism overhead.

If you had a million array elements to iterate, and nothing more than "i++;" inside the loop, then yeah, maybe the benefits of for() over .forEach() might be worth considering. But this is rarely the case.

over 1 year ago ·
27822
Identicon

Or use lodash's forEach implementation which is about as performant as the plain for loop.

over 1 year ago ·
28224
Gade cosmetics

Thanks for sharing a useful information.

11 months ago ·
28239
My stupid face

This is a terrible tip and I'll explain why.

  • Javascript has functions as a first class citizen. each/forEach is only slower because it creates a lexical scope around each loop iteration. In practice this is usually what you want.
  • 9/10 times you really want .map. You're probably looping in order to transform data.
  • loops favor side effects over pure functions. this means reaching into other scopes, and unpredictability. .map and functional approaches are objectively easier to test
  • if you have code where you are iterating so much that a for loop performance over map is so significant, you probably need to download lodash anyways.
  • if you really, really really must loop. (note: you probably don't) do NOT evaluate length in the iterator!! that gets called every time!
  • and if you REALLY must loop a while with a -- decrementor is actually even faster. Following the guidelines of asm.js are even better than that..Again, you probably do not need this in everyday practice, the tradeoof for testability and readability is not usually worth it.

Don't use loops. Don't use each. Use pure functions with no side effects. Map, filter, reduce.

11 months ago ·
28273

In My tests performance for forEach, is similar to (for(;;) loops, in smaller arrays, forEach is even faster, (for of) is the slowest unfortunately

10 months ago ·
28324
8c925222cb16151bbeeeb921600b15eb

I would use Array.forEach over for() any day.

10 months ago ·
28335

@the-simian, caching array.length outside of the iterator and reverse/decrementing loops are no longer necessarily faster. Reasonably modern JavaScript engines automatically optimise established patterns, such as forward loops and evaluating length - writing them in an "optimised way" prematurely simply adds confusion.

9 months ago ·
28355

I also make a compare test with native loop, native foreach, lodash foreach and underscoure foreach.
https://jsperf.com/for-loop-test-more
FYR

9 months ago ·
28370

for loops are really annoying when you're trying to build something complex, maintainability becomes harder, I think that there is a third solution http://gastrichealthtablet.org http://triflexcapsule.com

9 months ago ·
28376

Premature optimization!!!

9 months ago ·
28501

Thanks

7 months ago ·
28545
D532bee598a8e88d9c23274cfc0c0209

Don't use for(), because it is ugly

7 months ago ·
28612

thank you for allowing us to share information.
hopefully we are all in the given smoothness
http://www.rajanyaobatherbal.com/

7 months ago ·
28651

I think the description here is incorrect. It is not 95% slower. That would mean it runs 1/20 of the speed of the other. It is "...95% as fast..." or "...5% slower..." (which is the terminology used in the test link).

7 months ago ·
28720

This appears to no longer be true. The jsperf link showed for/forEach take about the same time in FF51.

6 months ago ·
29008
Konstrukt

This is valid only if you experience real performance problems. If not, it is premature optimisation at its best (or worst :) ). Main question here - what is more expensive to the company: code, running some miliseconds or microseconds slower, or the developers, spending minutes => hours => days reading it, trying to figure what all these loops all over the project actually do. :) Remember, we spend more time reading code, than writing it.
Actually, the example makes me want rewrite it to use map or reduce, instead of forEach (depending of what someFn does), but that's another story.

3 months ago ·
29054
16967604

Beyond coding style and personal philosophy, they do different things. One will step through each iteration synchronously; the other will run each function as separate in the event queue:

For example:
for (let i = 0; i < arr.length; i++) { setTimeout(() => { console.log(arr[i]); }, 100); }
will give a different result than
arr.forEach((ele) => { setTimeout(() => { console.log(ele); }; };
Run each and see the difference. If you are unfamiliar with asynchronous programming and the JavaScript event queue check out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
and
https://github.com/dillon-bostwick/async-recursive

3 months ago ·
29196

How about WHILE () {}??

28 days ago ·
29294

@avenger7x you could still have a closure with a for loop if you make the function outside the for loop

7 days ago ·
Awesome Job

7648e20a 9797 11e7 9df6 f1c7f530b0ea
Senior Full-Stack Web Developer
·
Remote (Virginia/US based company)
·
Full Time