为什么Array.forEach比Javascript中的for()循环慢? [英] Why Array.forEach is slower than for() loop in Javascript?

查看:164
本文介绍了为什么Array.forEach比Javascript中的for()循环慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我,在javascript中,array.forEach比循环慢的原因是什么。有什么特别的原因吗。

can anyone tell me whats the reason that array.forEach is slower than for loop in javascript. Is there any particular reason.

这是我试图找到性能的代码。

Here's the code that I was trying to find the performance.

// Populate the base array
    var arr = [];
    for (var i = 0; i < 1000; i++) {
      arr[i] = i;
    }

    function someFn(i) {
      return i * 3 * 8;
    }

使用Array.forEach:

Using Array.forEach :

arr.forEach(function (item){
  someFn(item);
})

使用for循环:

for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}

我在测试跑步者上测试了它。以下是结果:

I tested it on test runner . Here are the results:

正如您所见,Array.ForEach比for循环慢96%。
提前致谢。

As you can see Array.ForEach is 96% slower than for loop. Thanks in advance.

推荐答案

根据@BenAston& @trincot



粗略地说,这就是两种情况下发生的情况:

Updated based on feedback from @BenAston & @trincot

Roughly, this is what's happening in both cases:


  1. 将索引变量设置为初始值

  2. 检查是否退出循环

  3. 运行循环体

  4. 增加索引变量

  5. 返回步骤2

  1. Set the index variable to its initial value
  2. Check whether or not to exit the loop
  3. Run the body of your loop
  4. Increment the index variable
  5. Back to step 2

每次迭代发生的唯一开销是check&增量,这是非常低负荷的操作。

The only overhead that happens on every iteration is the check & the increment, which are very low-load operations.


  1. 实例化回调函数

  2. 检查是否存在要处理的下一个元素

  3. 使用新的执行上下文调用要处理的下一个元素的回调(这包括函数的范围;因此它的上下文,参数,内部变量和对任何外部变量的引用 - 如果使用的话)

  4. 运行回调的内容

  5. 拆除回拨函数电话

  6. 返回第2步

  1. Instantiate the callback function
  2. Check if there's a next element to process
  3. Call the callback for the next element to process, with a new execution context (this comprises the "scope" of the function; so its context, arguments, inner variables, and references to any outer variables -- if used)
  4. Run the contents of your callback
  5. Teardown of callback function call
  6. Return to step 2

功能设置的开销&拆除步骤3&这里的5比增量和增量大得多。检查vanilla for-loop的整数。

The overhead of the function setup & teardown in steps 3 & 5 here are much greater than that of incrementing & checking an integer for the vanilla for-loop.

也就是说,许多现代浏览器认识到&优化forEach调用,以及在某些情况下,forEach可能甚至更快!

That said, many modern browsers recognize & optimize forEach calls, and in some cases, the forEach might even be faster!

这篇关于为什么Array.forEach比Javascript中的for()循环慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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