How to make your program to be fast.
1. Use Pre Increment or Pre Decrement in place of Post Increment or Post Decrement operator.
i.e. use ++i or --i in place of i++ or i--.
Because ++i operator take increment and save it i.e. One CPU Instruction is required for it. and in case of i++ first save the value of i in register and then Increment, i.e. It takes two instruction set.
So My dear just imagine If you have a loop of 10000 . Then you can save 10000 CPU Instruction to be waste.
PRACTICE: Make Practice to write simple Loop as
Code:
for( i=0; i<n; ++i)
in place of
Code:
for( i=0;i<n; i++)
2. Use either for( i=n; i>=0;--i) or for( i=0;i<=n;++i)
Depends on CPU which are you using. Just check CPU Ticks in both cases which for loop is taking more time. mostly CPU give more efficiently on for( i=n; i>=0;--i)
3. Never use function call inside for loop. Make it redesign to be a for loop inside one function.
Example: In place of
for( i=n;i<=0;--i)
sum = Fun4Add(i);
use
Code:
Fun4Add(int num)
{
sum+=num;
}
Because No Overhead of creating stack frame, saving register etc in every loop and don't declare a variable in a loop and avoid to put any expression in a loop If that expression can be without loop with same output.
4. Don't Use Math library function pow(num1,num2) if num1 is multiple of 2. Because POW() library function is very costly. You can imagine about this arithmetic operation.
If num1==2 then use " Left shift Operator" num1< num2 . It is 100 times fast that Pow() library Function.
5. Always Declare any multi dimensions Array with the power Of 2.
example
int arr[2][1024] in place of int arr[1][1023] etc
int arr[32][128] in place of int arr[30][128] etc.
Because Reason is same as i have given in 4.
Asadullah Ansari
( Trueth can'nt be Changed)