David Granado David Granado - 1 year ago 48
Javascript Question

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

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

Nit Nit
Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download