原则

原则

Rob Pike’s 5 Rules of Programming

  • 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. 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.)
  • 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.

Pike’s rules 1 and 2 restate Tony Hoare’s famous maxim “Premature optimization is the root of all evil.”
Ken Thompson rephrased Pike’s rules 3 and 4 as “When in doubt, use brute force.”. Rules 3 and 4 are instances of the design philosophy KISS. Rule 5 was previously stated by Fred Brooks in The Mythical Man-Month. Rule 5 is often shortened to “write stupid code that uses smart objects”.

Rob Pike 的 5 个编程原则

  • 原则 1. 你没有办法预测每个程序的运行时间,瓶颈会出现在出乎意料的地方,所以在分析瓶颈原因之前,先不要盲目猜测。
  • 原则 2.测试(measure)。在测试之前不要优化程序,即使在测试之后也要慎重,除非一部分代码占据绝对比重的运行时间。
  • 原则 3.花哨的算法在 n 比较小时效率通常比较糟糕,而 n 通常是比较小的,并且这些算法有一个很大的常数。除非你确定 n 在变大,否则不要用花哨的算法。(即便 n 不变大,也要先遵循第 2 个原则。)
  • 原则 4.相对于朴素的算法来说,花哨的算法更容易出现Bug,更难调试。尽量使用朴素的算法和数据结构。
  • 原则 5.数据占主导地位(Data dominates)。如果你选择了正确的数据结构,并且已把事情组织好,那么算法的效率显而易见。编程的核心是数据结构是,不是算法。

Pike的第 1 条和第 2 条原则实际上重新强调了Tony Hoare那句名言,“过早的优化是万恶的根源”。
Ken Thompson将Pike的第 3 条和第 4 条原则改写为“当遇到麻烦时,试试最简单粗暴的办法”,原则 3 和原则 4 也是 KISS 哲学的体现。Fred Brooks在《人月神话》中首先阐述了原则 5 ,原则 5 常常会被概括为“用最佳结构,写简单代码”。

你可能感兴趣的:(原则)