kvzbpa
Last Updated: January 13, 2020
·
1.065M
· 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

5 Responses
Add your response

34730

How about for of loop ?

about 2 months ago ·
34735

very good

28 days ago ·
34745

Thank you for this site!

28 days 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?

about 1 month 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.

about 1 hour ago ·