为什么原生 javascript 数组 forEach 方法比标准 for 循环慢得多? [英] Why is native javascript array forEach method significantly slower than the standard for loop?

查看:46
本文介绍了为什么原生 javascript 数组 forEach 方法比标准 for 循环慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 Quintus 游戏引擎的源代码时,我发现他们大量使用 for 循环作为与原生 forEach 相对.

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.

我最初的想法是原生的 forEach 方法会比标准的 for 循环稍微快一点.但是,在使用这些基准测试 测试了我的理论之后,for 循环结构似乎明显更快了.

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?

明确地说,我在问为什么"这是这种情况.我不是在问哪个更快".

To be clear, I am asking "why" is this this case. I'm not asking "which is faster".

推荐答案

forEach 在内部包含许多检查,不像简单的循环那样直接.
有关详细信息,请参阅 Mozilla 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);
    }
  };
}

这篇关于为什么原生 javascript 数组 forEach 方法比标准 for 循环慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆