kvzbpa
Last Updated: February 29, 2020
·
1.085M
· afshinm

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

6 Responses
Add your response

34730

How about for of loop ?

4 months ago ·
34735

very good

4 months ago ·
34745

Thank you for this site!

4 months ago ·
34747

I wonder how often you actually need forEach anyway, you'll more often be using .map, .filter or .reduce anyway. Or is a for loop still faster?

3 months ago ·
34777

It is about how functional you want to be. A for loop is not that functional so I would sacrifice performance over maintainability and readability.

2 months ago ·
34818

I completely disagree with this & please allow to explain why:
Using for loops is easy enough sure, in most cases.. but your overlooking the entire point of map, forEach, filter, reduce, find, findIndex, etc... These make use of functional paradigms, and these paradigms exist for a reason. Functional programming is all about focusing not on how to solve problems and instead, shifts your focus to what to solve. Beyond that, anyone who is worried about performance at this level can go back after they've built their app and measure the app's performance and decide where to optimize (and I will bet you will find most of your optimizations will not be refactoring map, filter, or reduce). Using for loops is like going backwards, not to mention that forEach is slow because it is modifying/mutating the original array, whereas .map() returns a new array, is much faster, and without the side effect of mutating the original array. There are fewer and fewer cases where a for loop is viable. Currently, the best use case would be for something like iterating an async generator function using the new for-await-of syntax. Which is super cool. My point is that javascript gives us first class functions and in combination with it's (sorta) functional paradigms can produce: more readable code, better tooling, composition and patterns like higher order functions and currying, beautiful immutability, and many other wins such as referential transparency with pure functions - which reduce side effects and can increase run time, especially if memoized etc... Although I say "sorta" as obviously you're going to need functions with side effects to make API calls, or logs, or write i/o (any function that has I/O).

Regardless, I hate to say that I think you're giving bad advice here. Sure, everyone should know how to use all the original loops in javascript and use them well, but using a for loop versus map or even forEach (if you just have to mutate that existing array) is going the wrong direction.

28 days ago ·