Chapter 2: Introduction to compilers

Example of Optimizations

 

PI = 3.14159
3A+4M+1D+2E
Area = 4 * PI * R^2  
Volume = (4/3) * PI * R^3  
--------------------------------  
X = 3.14159 * R * R
3A+5M
Area = 4 * X  
Volume = 1.33 * X * R  
--------------------------------  

Area = 4 * 3.14159 * R * R 2A+4M+1D

Volume = ( Area / 3 ) * R

2A+4M+1D
--------------------------------  
Area = 12.56636 * R * R
2A+3M+1D
Volume = ( Area /3 ) * R  
--------------------------------  
X = R * R
3A+4M
   
A : assignment
M : multiplication
D : division
E : exponent
   
   

Example: see the following code,

int x = 2;

int y = 3;

int *array[5];

for (i=0; i<5;i++)

*array[i] = x + y;

Because x and y are invariant and do not change inside of the loop, their addition doesn't need to be performed for each loop iteration. Almost any good compiler optimizes the code. An optimizer moves the addition of x and y outside the loop, thus creating a more efficient loop. Thus, the optimized code in this case could look like the following:

int x = 5;

int y = 7;

int z = x + y;

int *array[10];

for (i=0; i<5;i++)

*array[i] = z;