Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Code Optimization

Tips and Tricks

About Me..

In this session..
Minimize local variables Declare local variables in the inner most scope Reduce the number of parameters Don't define a return value if not used Prefer int over char and short Prefer initialization over assignment Define lightweight constructors Loop jamming (Interesting..)

Minimize local variables


Try to use less local variables in a function, The compiler will be able to fit them into registers. This can result in considerable improvement due to two reasons:
All local variables are in registers Improves performance over accessing them from memory.

Declare local variables in inner most scope


Do not declare all the local variables in outer function scope. Performance is better if:
Local variables are declared in the inner most scope.

Example!

Reduce number of parameters


Function calls with large number of parameters may be expensive
Why??

Avoid passing complete structures as parameters.


Why??

Use pointers and references in such cases.


Why??

Don't define a return value if not used


The called function does not "know" if the return value is being used. It will always pass the return value. This return value passing may be avoided by not defining a return value which is not being used.

Prefer int over char and short


Prefer use of int over char and short. Perform arithmetic operations and parameter passing at integer level. If integer value can fit in a byte
Consider using an int to hold the number.

If you use a char, the compiler will first convert the values into integer, perform the operations and then convert back the result to char.

Prefer initialization over assignment


Example The number c is being initialized first by the instantiation and then by the assignment. Think about the optimized version!

Loop jamming..
Never use two loops where one will suffice. If you do a lot of work in the loop, it might not fit into your processor's instruction cache. Two separate loops are faster each one can run completely in the cache.

More tips..
Avoid using ++ and -- etc. within loop expressions. E.g.: while(n--){}, as this can sometimes be harder to optimize. Minimize the use of global variables. Declare anything within a file (external to functions) as static, unless it is intended to be global. Don't use recursion. Recursion can be very elegant and neat, but creates many more function calls which can become a large overhead. Avoid the sqrt() square root function in loops - calculating square roots is very CPU intensive. Single dimension arrays are faster than multi-dimension arrays. Single precision math may be faster than double precision there is often a compiler

You might also like