Compile Time Evaluation | Code Optimization
- Compile-time evaluation means shifting of computations from runtime to compilation.
- There are two methods used to obtain the compile time evaluation.
- In the folding technique, the computation of constant done at compile time instead of runtime.
example : length = (22/7) * d
- Here folding implied by performing the computation of 22/7 at compile time
- In this technique, the value of variable replaced and computation of an expression done at the compilation time.
example : pi = 3.14; r = 5;
Area = pi * r * r
- Here at the compilation time, the value of pi replaced by 3.14 and r by 5 then the computation of 3.14 * 5 * 5 is done during compilation.
Common Sub Expression Elimination Code Optimization
- The common subexpression is an expression appearing repeatedly in the program which is computed previously.
- Then if the operands of this subexpression do not get changed at all then result of such subexpression is used instead of recomputing it each time
t1 := 4 * i
t2 := a[t1]
t3 := 4 * j
t4 : = 4 * i
t6 := b[t4]+t5
- The above code can optimize using common subexpression elimination
- The common subexpression t4:= 4 * i eliminated as its computation is already in t1 and value of i not been changed from definition to use.
Loop invariant computation (Frequency reduction) | Code Optimization
- Loop invariant optimization can obtain by moving some amount of code outside the loop and placing it just before entering in the loop.
- This method also called code motion.
Can be optimized as a
Strength Reduction Code Optimization
- Strength of certain operators is higher than others.
- For instance strength of * is higher than +.
- In this technique, the higher strength operators can replace by lower strength operators.
count = i x 7;
- Here we get the count values as 7, 14, 21 and so on up to less than 50.
- This code can replace by using strength reduction as follows
count = temp;
temp = temp+7;
Dead Code Elimination | Code Optimization
- A variable said to be live in a program if the value contained into is subsequently.
- Moreover, On the other hand, the variable said to be dead at a point in a program if the value contained into it never used.
- The code containing such a variable supposed to a dead code. And an optimization can perform by eliminating such a dead code.
- if statement a dead code as this condition will never get satisfied hence, statement can eliminated and optimization can done.