Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is native javascript array forEach method significantly slower than the standard for loop? [duplicate]

Tags:

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".

like image 263
Just a guy Avatar asked Mar 03 '14 19:03

Just a guy


People also ask

Is forEach slower than for loop JavaScript?

forEach Loop It is faster in performance. It is slower than the traditional loop in performance.

Why is forEach slower than for?

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.

Is array forEach faster than for loop?

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.

Which is faster forEach or for loop JavaScript?

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.


1 Answers

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);
    }
  };
}
like image 197
Etheryte Avatar answered Oct 09 '22 15:10

Etheryte