Yuto Blog
speaker-deck-iconyoutube-iconrss-iconx-icongithub-icon

BiomeがforEachではなくfor...ofを推す理由を処理速度の観点から見る

publishedAt:
2024/06/29
updatedAt:
目次

Intro

biomeにはforEachを使用すると、for...ofを使用するようにエラーが出ます。これはnoForEachというrecommendedルールによるものです。

今回はなぜfor...ofを使うように推奨しているのかを、処理速度の観点で見ていきます。

お断り

Performance: Using forEach can lead to performance issues, especially when working with large arrays. When more requirements are added on, forEach typically gets chained with other methods like filter or map, causing multiple iterations over the same Array. Encouraging for loops discourages chaining and encourages single-iteration logic (e.g. using a continue instead of filter).

本記事でも出てきますが。noForEachのドキュメントにはこのように記載されています。 筆者は今回の記事でこのことについての説明をしているようなものなので、その他のJavaScriptのメソッドを使った比較などは行ってないです。

あくまでも今回はforEachfor...ofの違いについてという内容であるということをご理解いただければと思います🙇‍♂️

Performance

ドキュメントには以下のように記載されています。

Performance: Using forEach can lead to performance issues, especially when working with large arrays. When more requirements are added on, forEach typically gets chained with other methods like filter or map, causing multiple iterations over the same Array. Encouraging for loops discourages chaining and encourages single-iteration logic (e.g. using a continue instead of filter).

要件が追加される場合、つまり何かしら配列の操作を行う必要があるときに、forEachではmapやfilterを組み合わせますが、それだと毎回Arrayに対して読み込みが発生してしまいます。

それに対しfor...ofではcontinue, breakなどが使用出来るので、Arrayを一度読み込むだけで済むことができるという違いがあります。

計測

forEachとfor...ofの実行時間を

この二つのパターンで計測してみました。リポジトリはこちらに貼っているので、もし手元で動かしてみたい方はどうぞ。

https://github.com/yossydev/biome-noForEach

結果

1. 配列の値一つ一つに対して処理を行うパターン

- forEach: 6.912ms
- for...of: 10.796ms

2. 配列に対して少し要件を追加して処理を行うパターン

- forEach with map and filter: 20.497ms
- for...of with continue: 12.882ms

2. 配列に対して少し要件を追加して処理を行うパターン

- forEach with filter and forEach: 14.519ms
- for...of with continue and break: 11.689ms

1ではforEachの方が早いものの、filterを組み合わせた2ではfor...ofの方が早いことがわかりました。 これは複数のメソッドチェーンがArrayに対して何度も読み込みが発生してしまうことよる処理速度の差であると考えられます。

まとめ

筆者としてはfor...ofの方が明示的になるのでコードが読みやすいので好きでしたが、処理速度という観点でも差があることが理解できたので良かったです。

関連

0