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

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

问题描述

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

我原来的想法是,本地forEach方法会比标准的循环略快。但是,在使用这些基准测试测试我的理论之后,for循环结构看起来要快得多。 / p>

翻遍后,我似乎无法找出底下发生了什么事。有谁知道这个巨大差异的原因吗?编辑:为了说清楚,我问为什么是这样的情况。我不是问哪个更快。
解决方案

forEach在内部包含许多检查,并不像一个简单的循环。

请参阅 Mozilla Javascript参考

$ p $ if(!Array.prototype.forEach)
{
Array.prototype.forEach = fun(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?参数[1]:void 0;
for(var i = 0; i {
if(i in t)
fun.call(thisArg,t [i],i,吨);
}
};
}


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

解决方案

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天全站免登陆