In the following example:
a = b * c + g;
d = b * c * d;
it may be worth (ie, program executes faster) transforming the code so that it is translated as if it had been written:
tmp = b * c;
a = tmp + g;
d = tmp * d;
The cost/benefit analysis performed by an optimizer will calculate whether the cost of the store to
tmp is less than the cost of the multiplication; in practice other factors such as which values are held in which registers are also significant.
In simple cases like this, programmers may manually eliminate the duplicate expressions while writing the code. The greatest source of CSEs are intermediate code sequences generated by the compiler, such as for array indexing calculations, where it is not possible for the developer to manually intervene. In some cases language features may create many duplicate expressions. For instance, C macros, where macro expansions may result in common subexpressions not apparent in the original source code.
The benefits of performing CSE are great enough that it is a commonly used optimization.
Compilers need to be judicious about the number of temporaries created to hold values; an excessive number of temporary values creates register pressure possibly resulting in spilling registers to memory, which may take longer than simply recomputing an arithmetic result when it is needed.
Compiler writers distinguish two kinds of CSE: