JS 迴圈與效能

JS 常見的 for 迴圈

以下由執行速度的快到慢排序

  • for-loop-cached
1
2
3
4
const listSize = yourList.length; // 精華
for (let index = 0; index < listSize; index++) {
  // ...
}
  • for-loop
1
2
3
for (let index = 0; index < yourList.length; index++) {
  // ...
}
  • forEach
1
2
3
yourList.forEach((element) => {
  // ...
});
  • for-of
1
2
3
for (const element of yourList) {
  // ...
}

參考資料

https://dev.to/siddiqus/which-for-loop-is-the-fastest-in-javascript-4hdf

0%