JavaScript 的 for-of 循环实际上很快(V8)
Published on 01/01/2026
Updated on 14/01/2026
发布于 01/01/2026
更新于 14/01/2026
When it comes to iterating over arrays, for...of loops are believed to be significantly slower than traditional indexed loops. This has some grounding, since for-of loops are based on the iteration protocol, where the iterator has next() method returning an object like this: { value: /* element value */, done: /* a boolean, indicating the end of iteration */ }. Obviously, returning such object for every element will add an overhead.
在遍历数组时,for...of 循环被认为比传统的索引循环慢得多。这是有根据的,因为 for-of 循环基于 iteration protocol,其中迭代器有一个 next() 方法,返回像这样的对象:{ value: /* element value */, done: /* a boolean, indicating the end of iteration */ }。显然,为每个元素返回这样的对象会增加开销。
However, I decided to test this since JS engines are constantly improving and sometimes can do amazing optimizations.
然而,我决定测试一下,因为 JS 引擎在不断改进,有时能进行惊人的优化。
Table of contents
目录
The benchmark
基准测试
I decided to do the benchmarks with jsbenchmark.com on Chrome 143, Windows 11 and AMD Ryzen 5000U. All the benchmark tests are run sequentially.
我决定使用 jsbenchmark.com 在 Chrome 143、Windows 11 和 AMD Ryzen 5000U 上进行基准测试。所有基准测试都是顺序运行的。
The core idea of the benchmark
基准测试的核心思想
The idea is to create 5 types of arrays: integers, floats, strings, objects and mixed values.
这个想法是创建 5 种类型的数组:整数、浮点数、字符串、对象和混合值。
- The benchmarks will be done with 3 array sizes: 5000, 50000, and 500000.
- 基准测试将使用 3 种数组大小进行:5000、50000 和 500000。
- There will be 6 types of loops:
-
Classic for with i++:
for (let i = 0; i < arr.length; i++) { DATA.doSomethingWithValue(arr[i]); } -
Classic for with i++ and cached array length:
const length = arr.length; for (let i = 0; i < length; i++) { DATA.doSomethingWithValue(arr[i]); } -
Classic for with i-- reversed:
for (let i = arr.length - 1; i >= 0; i--) { DATA.doSomethingWithValue(arr[i]); } -
for-of:
for (const x of arr) { DATA.doSomething...
-