Thursday, November 15, 2007

How to make application Faster C++/C

Following small optimaization can make applications more faster . I think.

1.Make small functions  as inline functions.

2. If you are  using variable to hold constant data , make in const.
like int i = MAX_VAL; can be changed to const int i = MAX_VAL

3.Creating simple expressions
some exmaples like belowif(i == MAX_VAL) return 1;
else return 0 ; 
can be replaced with return ( i==MAX_VAL); 

another one if( i ==0 ) return nVal; else returrn 0; can be replaced with  return (i==0) ?nVal : 10   Ternary operator is fast than if else.
4.When function calling don't pass long arrays . Use pointers or reference.

5.For copying array use api , like CopyMEmory , memcpy.
(They uses asm codes to get the tas done)

6. similarly for initializing memset also can be used .

7. When increamenting class objects uses ++obj , rather than obj++. 
(because obj++ might create  temporary objects).

8. Too much object oriented approch will also affect speed.

9. when one function called ,  It is wise to return first if any argument is invalid , rather than do it later.
   if(param == 0 || param1 = 0 || n!=V) return 0;
   return 1;

10. Allocating memory several times wil cause fragmentation, so allocate a buffer pool first.

11. Similarly try to avoid creating mutiple files in Hard disk .It will also cause fragmentation.
      Try to do the work with one file, otherwise think about databases.

12.  Use int , as loop couner etc. Because int size same as the processor register size, so it is fast than others.

13.  Exception catching is expensive , it will cause application slower , and will increase the size of  EXE.

Do if you are not using exception handleres , you can turn it off in compiler settings
Also avoid putting exception handling inside repeatedlycalling functions .
Put exception handling on in the main parts of program.

 14. you can use __fastcall to make functions calls faster , it wil try to put arguments in registers._cdecl will increase the size of EXE.

 15. Don't load all DLLs on application loading . Most of the cases applications slowing down due to these reasons.
 DLL as name implies is for dynamic loading.

16. Most important , Before copying code from somwhere Understand it :)