can anyone tell me whats the reason that array.forEach is slower than for loop in javascript. Is there any particular reason.
Here's the code that I was trying to find the performance.
// Populate the base array
var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
Using Array.forEach :
arr.forEach(function (item){
someFn(item);
})
Using for loop :
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
I tested it on test runner . Here are the results:
As you can see Array.ForEach is 96% slower than for loop. Thanks in advance.
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.
This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.
forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.
Roughly, this is what's happening in both cases:
The only overhead that happens on every iteration is the check & the increment, which are very low-load operations.
The overhead of the function setup & teardown in steps 3 & 5 here are much greater than that of incrementing & checking an integer for the vanilla for-loop.
That said, many modern browsers recognize & optimize forEach calls, and in some cases, the forEach might even be faster!
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