16 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.

C’s good performance is often cited as one of the main reasons it 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 of 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.

16.1 Inline functions

16.2 Using restrict qualifiers

16.3 Unsequenced and reproducible attributes

16.4 Measurement and inspection

Summary