Chapter 8 - Code Optimization Part 2
Chapter 8 - Code Optimization Part 2
Code Optimization
➢ Optimization is a program transformation technique, which tries to improve the code by making it
consume less resources (i.e. CPU, Memory) and deliver high speed.
➢ Code optimization is any method of code modification to improve code quality and efficiency.
➢ The process of code optimization involves-
o Eliminating the unwanted code lines
o Rearranging the statements of the code
➢ Goals of code optimization:
o Remove redundant code without changing the meaning of program.
o Reduce code size
o Efficient memory usage
o Yielding better performance.
➢ The i/p and o/p of the code optimizer is intermediate code. However, the code is an optimized set
of intermediate stmts.
Some optimization techniques include
I. Dead code elimination
Variable is live at a point in a program if its value can be used subsequently otherwise, it is dead at that
point. A related idea is dead (or useless) code statements that compute values that never get used.
Thus, dead code plays no role in any program operation and therefore it can simply be eliminated. Code
that is unreachable or that does not affect the program (e.g. dead stores) can be eliminated too.
Example:1
In the example below, the value assigned to i is never used, and the dead store can be eliminated. The
first assignment to global is dead, and the third assignment to global is unreachable; both can be
eliminated.
int global;
void f ()
{
int I;
i = 1; /* dead store */
global = 1; /* dead store */
global = 2;
return;
global = 3; /* unreachable */
}
Code fragment after dead code elimination.
o Loop Jamming
Loop jamming is the combining the two or more loops in a single loop. It reduces the time taken
to compile the many number of loops.
Example:
Initial code optimized code
for (int i=0; i<5; i++) for (int i=0; i<5; i++)
a= i+5; { a= i+5;
for (int i=0; i<5; i++) b= i+ 10;
b= i+ 10; }
III. Induction variables
➢ Are variables such that every time they change value, they are incremented or decremented.
➢ Basic induction variable: induction variable whose only assignments within a loop are of the
form: i = i +/- C, where C is a constant.
➢ Primary induction variable: basic induction variable that controls the loop execution
(for i=0; i<100; i++) i (register holding i) is the primary induction variable.
➢ Derived induction variable: variable that is a linear function of a basic induction variable.
Example:
Initial code optimized code
s=3*i+1; s=3*i+1;
while(i<10) { while(s<31)
a[s]=a[s]-2; { a[s]=a[s]-2;
i=i+2//induction variable s=s+6;
s=s+6; }
}
Example 2
Initial code optimized code
2
B= A B=A+A
The expression “A x 2” is replaced with the expression “A + A”.
For above example, on most computers a multiplication takes more time to execute than does an addition.
This is especially true on many of today’s minicomputers