7 Opinionated optimization

 

This chapter covers

  • Embracing premature optimization
  • Taking a top-down approach to performance problems
  • Optimizing CPU and I/O bottlenecks
  • Making safe code faster and unsafe code safer

Programming literature on optimization always starts with a well-known quote by the famous computer scientist Donald Knuth: “Premature optimization is the root of all evil.” Not only is the statement wrong, but it’s also always misquoted. First, it’s wrong because everybody knows that the root of all evil is object-oriented programming since it leads to bad parenting and class struggles. Second, it’s wrong because the actual quote is more nuanced. This is almost another case of lorem ipsum, which is gibberish because it is quoted from the middle of an otherwise meaningful Latin text. Knuth’s actual statement is, “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”1

7.1 Solve the right problem

7.1.1 Simple benchmarking

7.1.2 Performance vs. responsiveness

7.2 Anatomy of sluggishness

7.3 Start from the top

7.3.1 Nested loops

7.3.2 String-oriented programming

7.3.3 Evaluating 2b || !2b

7.4 Breaking the bottle at the neck

7.4.1 Don’t pack data