简体   繁体   English

为什么 for...of 循环比传统的 for 循环慢得多?

[英]Why is for...of loop so much slower than the traditional for loop?

I setup a simple benchmark for comparing performance of for (const x of arr) and for (let i = 0; i < arr.length; i++) loops.我设置了一个简单的基准来比较for (const x of arr)for (let i = 0; i < arr.length; i++)循环的性能。 ( benchmark link ) 基准链接

Setup code设置代码

const arr = [...new Array(10000)].map(() => Math.random());

for (let i = 0; i < arr.length; i++)

let sum = 0;
for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
}

for (const x of arr)

let sum = 0;
for (const x of arr) {
    sum += x;
}

I have re-run the benchmark several times over, and each time, the for-of loop is almost 70% slower than the for-length loop.我已经多次重新运行基准测试,每次, for-of循​​环都比for-length循环慢了近 70%。 (~150k ops/sec vs ~43k ops/sec). (~150k ops/sec vs ~43k ops/sec)。 This is very surprising to me.这对我来说非常令人惊讶。

What is the reason for this loop being significantly slower?这个循环明显变慢的原因是什么?

I have looked at the related thread and the answers there dive into pros/cons of micro-benchmarking, and the conclusion was that switching the test order results in flipping the result.我查看了相关线程,其中的答案深入探讨了微基准测试的优缺点,结论是切换测试顺序会导致结果翻转。 My case is different because I have large arrays (so no micro-bench issues) and I am using a test framework (jsbench.me) to avoid cold start issues.我的情况不同,因为我有很大的 arrays(所以没有微型工作台问题)并且我正在使用测试框架(jsbench.me)来避免冷启动问题。

for...of accesses @iterator method ( obj[Symbol.iterator] to access), which is a generator function that contains the for...length loop inside with yield statements for...of 访问@iterator方法( obj[Symbol.iterator]访问),这是一个生成器 function ,其中包含 for...length 循环和yield语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM