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

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

问题描述

谁能告诉我 array.forEach 比 javascript 中的 for 循环慢的原因是什么.有什么特别的原因吗.

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 (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}

我在 test runner 上进行了测试.结果如下:

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 & 的反馈更新@特林科特

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

Updated based on feedback from @BenAston & @trincot

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

  1. 将索引变量设置为其初始值
  2. 检查是否退出循环
  3. 运行循环体
  4. 增加索引变量
  5. 返回第 2 步

每次迭代发生的唯一开销是检查 &增量,这是非常低负载的操作.

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 步

函数设置的开销&拆解步骤 3 &5 这里比递增 & 大得多.检查原版 for 循环的整数.

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