Compiler Design and Construction - Old Questions

11. Why is it necessary to optimize code? Explain any two code optimization techniques with example.

5 marks | Asked in Model Question

Code optimization is used to improve the intermediate code so that the output of the program could run faster and takes less space. It removes the unnecessary lines of the code and arranges the sequence of statements in order to speed up the program execution without wasting resources. It tries to improve the code by making it consume less resources (i.e. CPU, Memory) and deliver high speed.

Optimization is necessary in the code generated by simple code generator due to the following reasons:

  • Code optimization enhances the portability of the compiler to the target processor.
  • Code optimization allows consumption of fewer resources (i.e. CPU, Memory).
  • Optimized code has faster execution speed.
  • Optimized code utilizes the memory efficiently.
  • Optimized code gives better performance.
  • Optimized code often promotes re-usability.

Code optimization techniques are:

1. Common-Subexpression Elimination: In the common sub-expression, we don't need to be computed it over and over again. Instead of this we can compute it once and kept in store from where it's referenced when encountered again. For e.g.


2. Dead Code Elimination: The dead code may be a variable or the result of some expression computed by the programmer that may not have any further uses. By eliminating these useless things from a code, the code will get optimized. For e.g.