CPP‐Optimizations - rFronteddu/general_wiki GitHub Wiki

When the compiler optimizes a program, the result is that variables, expressions, statements, and function calls may be rearranged, modified, replaced, or removed entirely. Such changes can make it hard to debug a program effectively. To help minimize such issues, debug builds will typically leave optimizations turned off, so that the compiled code will more closely match the source code.

Some optimizations

  • Constant folding: Constant folding is an optimization technique where the compiler replaces expressions that have literal operands with the result of the expression. Using constant folding, the compiler would recognize that the expression 3 + 4 has constant operands, and then replace the expression with the result 7.
  • Constant propagation: Constant propagation is an optimization technique where the compiler replaces variables known to have constant values with their values. Using constant propagation, the compiler would realize that x always has the constant value 7, and replace any use of variable x with the value 7. This removes the need for the program to go out to memory to fetch the value of x.
  • Dead Code Elimination: Dead code elimination is an optimization technique where the compiler removes code that may be executed but has no effect on the program’s behavior. When a variable is removed from a program because it is no longer needed, we say the variable has been optimized out (or optimized away).
  • Const variables are easier to optimize: Because x is now const, the compiler has a guarantee that x can’t be changed after initialization. This makes it more likely the compiler will apply constant propagation, and then optimize the variable out entirely.

Nomenclature

Constants in C++ are sometimes divided into two informal categories.

A compile-time constant is a constant whose value is known at compile-time. Examples include:

  • Literals.
  • Constant objects whose initializers are compile-time constants.

A runtime constant is a constant whose value is determined in a runtime context. Examples include:

  • Constant function parameters.
  • Constant objects whose initializers are non-constants or runtime constants.

Although you will encounter these terms out in the wild, in C++ these definitions are not all that useful:

  • Some runtime constants (and even non-constants) can be evaluated at compile-time for optimization purposes (under the as-if rule).
  • Some compile-time constants (e.g. const double d { 1.2 };) cannot be used in compile-time features (as defined by the language standard).

For this reason, we recommend avoiding these terms.