While reading the source code for the Quintus game engine, I found that they were making heavy use of for loops as opposed to the native forEach.
My original thought was that the native forEach method would be slightly faster than standard for loops. However, after testing my theory with these benchmarks, the for loop structures appears to be significantly faster.
After poking around, I can't seem to find out what's going on under the hood. Does anyone know the reason for the huge difference?
EDIT: To be clear, I am asking "why" is this this case. I'm not asking "which is faster".
forEach Loop It is faster in performance. It is slower than the traditional loop in performance.
Deductions. 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.
The FOR loop without length caching and FOREACH work slightly faster on arrays than FOR with length caching. Array. 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.
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.
The forEach includes many checks internally and isn't as straight forward as a simple loop.
See the Mozilla Javascript reference for the details:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisArg */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t)
fun.call(thisArg, t[i], i, t);
}
};
}
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