无聊的测试
今天突然突发奇想想要测试一波遍历数组的性能,结果真的很意外呀
代码
const array =Object.keys(Array.from({length:10000000}))
console.time();
array.forEach(element => {
});
console.timeEnd();
//foreach 104.966ms 103.549ms 130.645ms
const array =Object.keys(Array.from({length:10000000}))
console.time();
for (const key in array) {
const item = array[key];
}
console.timeEnd();
//forin 2280.834ms 2213.344ms 2268.358ms
const array =Object.keys(Array.from({length:10000000}))
console.time();
for (const item of array) {
}
console.timeEnd();
//forof 404.071ms 383.066ms 442.527ms
```js
const array =Object.keys(Array.from({length:10000000}))
console.time();
for (let i = 0; i < array.length; i++) {
const element = array[i];
}
console.timeEnd();
//for 282.617ms 243.459ms 228.622ms
结论
真的很意外,没想到foreach是最快的,我一直以为foreach内部是用for实现的,看来不是
//for 282.617ms 243.459ms 228.622ms
//forof 404.071ms 383.066ms 442.527ms
//forin 2280.834ms 2213.344ms 2268.358ms
//foreach 104.966ms 103.549ms 130.645ms
foreach > for > forof > forin