Suppose I have the following C code:
int i = 5;
int j = 10;
int result = i + j;
If I'm looping over this many times, would it be faster to use int result = 5 + 10? I often create temporary variables to make my code more readable, for example, if the two variables were obtained from some array using some long expression to calculate the indices. Is this bad performance-wise in C? What about other languages?
A modern optimizing compiler should optimize those variables away, for example if we use the following example in godbolt with
gccusing the-std=c99 -O3flags (see it live):it will result in the following assembly:
for the calculation of
i + j, this is form of constant propagation.Note, I added the
printfso that we have a side effect, otherwisefuncwould have been optimized away to:These optimizations are allowed under the as-if rule, which only requires the compiler to emulate the observable behavior of a program. This is covered in the draft C99 standard section
5.1.2.3Program execution which says:Also see: Optimizing C++ Code : Constant-Folding