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

StackOverflow https://stackoverflow.com/questions/22155280

Question

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

Was it helpful?

Solution

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);
    }
  };
}

OTHER TIPS

thanks for pasting the implementation; there's the answer right there: fun.call is slower than fun, and the i in t test is expensive.

Seems to have tried so hard to address uncommon cases that the final result is too expensive for common use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top