为什么原生javascript数组forEach方法明显慢于循环标准?

Dav*_*ado 19 javascript arrays performance foreach

在阅读Quintus游戏引擎的源代码时,我发现他们正在大量使用for循环而不是原生forEach.

我原来的想法是,原生的forEach方法比循环的标准稍快.然而,在用这些基准测试我的理论之后,for循环结构看起来明显更快.

在探索之后,我似乎无法找出引擎盖下发生了什么.有谁知道巨大差异的原因?

编辑:要清楚,我问这个案子是"为什么".我不是在问"哪个更快".

Nit*_*Nit 17

forEach在内部包含许多检查,并不像简单循环那样简单.
有关详细信息,请参阅Mozilla Javascript参考:

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);
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

  • @DavidGranado 2017年的任何更新将不胜感激 (5认同)
  • 好点子.然而,由于这都是原生的,我希望这种影响远远小于20倍的性能差异.我认为它可能是这个和这个阻止函数内联的某种组合.我将从这些新观点中挖掘更多内容. (2认同)