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
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. It's possible the engine is able to optimize thesomeFn
function which means it doesn't need to make a function call. Perhaps you can modify your performance test to check this.forEach
is slower, unlike the JSPerf (which i don't trust) results, it's only slightly slower... Yet sometimes it can turn out to be significantly faster than thefor
loop. Check this out.