5つのルール — 詳細解説
Rule 1: ボトルネックは予想外の場所にある
"You can't tell where a program is going to spend its time. Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you've proven that's where the bottleneck is."
プログラムがどこで時間を費やすかは、事前に予測できない。ボトルネックは驚くような場所に現れるものだ。だから、そこが本当にボトルネックだと証明できるまで、当て推量で速度ハックを入れてはいけない。「ここが遅いはずだ」という直感は、ほとんどの場合外れる。
Rule 2: 計測せよ
"Measure. Don't tune for speed until you've measured, and even then don't unless one part of the code overwhelms the rest."
計測せよ。速度のチューニングは計測してからにすること。計測した上でも、コードの一部分が他を圧倒的に支配している場合にのみチューニングすべきだ。感覚ではなくデータに基づいて判断する。プロファイラを使え、ということ。
Rule 3: nが小さいとき、高級アルゴリズムは遅い
"Fancy algorithms are slow when n is small, and n is usually small. Fancy algorithms have big constants. Until you know that n is frequently going to be big, don't get fancy. (Even if n does get big, use Rule 2 first.)"
高級なアルゴリズムはnが小さいとき遅い。そしてnは大抵小さい。高級なアルゴリズムには大きな定数係数がつきまとう。nが本当に大きくなると分かるまで、凝ったことをするな。たとえnが大きくなるとしても、まずはRule 2(計測)を先にやれ。O(n log n)の華麗なソートより、O(n^2)の素朴なソートの方が、n=20なら速いことがある。
Rule 4: シンプルなアルゴリズムとデータ構造を使え
"Fancy algorithms are buggier than simple ones, and they're much harder to implement. Use simple algorithms as well as simple data structures."
高級なアルゴリズムは単純なものよりバグが多く、実装もはるかに難しい。シンプルなアルゴリズムとシンプルなデータ構造を使え。複雑さはバグの温床であり、保守コストを爆発させる。読めるコード、理解できるコードが最良のコードだ。
Rule 5: データが支配する
"Data dominates. If you've chosen the right data structures and organized things well, the algorithms will almost always be self-evident. Data structures, not algorithms, are central to programming."
データが支配する。正しいデータ構造を選び、物事をうまく整理すれば、アルゴリズムはほぼ自明になる。プログラミングの中心にあるのはアルゴリズムではなく、データ構造だ。これは最も深い洞察であり、「まずデータの形を考えろ、コードは後からついてくる」という設計哲学の核心を突いている。
歴史的な文脈
Tony Hoareとの関連:Rule 1とRule 2は、Hoareの有名な格言「早すぎる最適化は諸悪の根源」(premature optimization is the root of all evil)と同じ精神を共有している。
Ken Thompsonの要約:Rule 3とRule 4について、Thompsonは「迷ったら力任せでやれ」(When in doubt, use brute force)と簡潔にまとめた。
Fred Brooksとの響き合い:Rule 5は、Brooks著『人月の神話』で述べられた「データ構造を見せてくれれば、コードは要らない」という考え方と通じている。