Rob Pike's 5 Rules of Programming

⭐⭐⭐⭐ 4星 | 来源: cs.unc.edu

来自 Bell Labs 的经典编程智慧,Rob Pike 提出的 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: 先测量

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.

Rule 4: 简单算法更少 bug

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.

简言之:写"使用智能对象的愚笨代码"

名人点评

  • Rule 1 & 2 ← Tony Hoare: "Premature optimization is the root of all evil."
  • Rule 3 & 4 ← Ken Thompson: "When in doubt, use brute force."
  • Rule 5 ← Fred Brooks: 《人月神话》

哲学基础

这些规则是 KISS 原则 (Keep It Simple, Stupid) 的经典阐述:

  • 数据 > 算法:好的数据结构让算法自明
  • 简单 > 复杂:简单算法 bug 更少、易实现
  • 测量 > 猜测:优化前先有数据支撑
阅读原文 →