为什么Array.forEach比Javascript中的for()循环慢? [英] Why Array.forEach is slower than for() loop in Javascript?
问题描述
任何人都可以告诉我,在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:
- 将索引变量设置为初始值
- 检查是否退出循环
- 运行循环体
- 增加索引变量
- 返回步骤2
- Set the index variable to its initial value
- Check whether or not to exit the loop
- Run the body of your loop
- Increment the index variable
- Back to step 2
每次迭代发生的唯一开销是check&增量,这是非常低负荷的操作。
The only overhead that happens on every iteration is the check & the increment, which are very low-load operations.
- 实例化回调函数
- 检查是否存在要处理的下一个元素
- 使用新的执行上下文调用要处理的下一个元素的回调(这包括函数的范围;因此它的上下文,参数,内部变量和对任何外部变量的引用 - 如果使用的话)
- 运行回调的内容
- 拆除回拨函数电话
- 返回第2步
- Instantiate the callback function
- Check if there's a next element to process
- 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)
- Run the contents of your callback
- Teardown of callback function call
- 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屋!