Chapter 15. Performance
This chapter covers
- Writing inline functions
- Restricting pointers
- Measuring and inspecting performance
Once you feel more comfortable when coding in C, you will perhaps be tempted to do complicated things to “optimize” your code. Whatever you think you are optimizing, there is a good chance you will get it wrong: premature optimization can do a great deal of harm in terms of readability, soundness, maintainability, and so on. Knuth [1974] coined the following phrase that should be your motto for this whole level:
Takeaway D
Premature optimization is the root of all evil.
Its good performance is often cited as one of the main reasons C is used so widely. While there is some truth to the idea that many C programs outperform code of similar complexity written in other programming languages, this aspect of C may come with a substantial cost, especially concerning safety. This is because C, in many places, doesn’t enforce rules, but places the burden of verifying them on the programmer. Important examples for such cases are
- Out-of-bounds access of arrays
- Accessing uninitialized objects
- Accessing objects after their lifetime has ended
- Integer overflow
These can result in program crashes, loss of data, incorrect results, exposure of sensitive information, and even loss of money or lives.
Takeaway 15.1
Do not trade off safety for performance.