Optimizing tips for C++

Few tips in C++ to optimize the code:

--> Data Types:

1. Using of 'int' instead of char or short.

Its good to use the data type 'int' instead of 'char' or 'short' wherever possible.
Explanation: Data type 'int' is always the native type for the machine.

--> Operators

1. Arithmetic operations.

Addition is always faster than multiplication and multiplication is faster than division. And bit wise operations are faster than any other Operation. Where ever possible see if you can write the optimized code. This optimized code, will save a lot of time and system resources. 

2. Use 'op='.

Wherever possible, use 'op=' in favour of 'op'. For example, use

myShape += value;
rather than
myShape = myShape + value;
Explanation: The first version is better than the second because it avoids creating a temporary object.

3. if-else.

Every 'if' should have corresponding 'else'.
Eg:
if(a>b)
{
     something ;
}
rest_of_code;


Instead of the above code, write code like below:
if(a>b)
{
     something ;
}
else ; // Blank else statement.
rest_of_code;


Explanation: Compiler takes a lot of time to evaluate next statement if the condition fails in case where 'else' is not mentioned. So, its good practice to use blank 'else' statement.

4. if-else vs. Switch.

Whereever possible use switch-case insted of nested if-else. Also keep the most common used options on top of switch-case for better performance.

--> Loops

1. Going back in loop.

Its good practice to count down to zero rather than upto n.
Eg:
for (i = n; i > 0; --i)
rather than for (i = 0; i <=n; i++) 
Explanation: ++i is faster than i++. Also testing with zero is faster than testing with anything else.

--> Functions

1. Local Functions to be defined as Static.

Declare local functions as static, as they will not be visible to functions outside the ".cpp" file. Also some C++ compilers will optimize if we declare this as static.
Eg: static void foo()

2. Small Functions to be declared as 'Inline'.

If the function definition is small, say 2-4 lines of code, then its good idea to define them as 'Inline' instead of normal functions. Another factor to consider is how many times that function is called. If it is called so many times, then prefer 'Inline' for small functions to increase the performance.
Eg:
inline void foo()
Explanation: All 'Inline' function definition is duplicated in the body of the function where ever it is called from. As it is duplicated, it will increase the performance as no function swapping is required during function calls.

3. Function parameters.
When passing function parameters its good to pass by reference rather than by value.
Eg:
void foo(Shape &myShape)
rather than
void foo(Shape myShape)

Comments

Popular posts from this blog

GCC Extenstion

What is Code Bloat?