September 19, 2008

[C/C++] - C++ optimizations for loops, if/else and switch/case statements

1- Optimize For Loops

Where-ever possible, count down to zero rather than up to n. For example, use

for (i = n-1; i >= 0; --i)

rather than

for (i = 0; i <>

The test is done every iteration and it's faster to test against zero than anything else. Note also that

++i

is faster than

i++

when it appears in the third part of the for loop statement.

2- Optimize If Statements

Factor out jumps. For example, use

bar();

if (condition)

{

undoBar();

foo();

}

rather than

if (condition)

{

foo();

}

else

{

bar();

}

Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping.

3- Optimize Switch Statements

Put the most common cases first.


2 comments:

trss said...

i've heard ++i being faster than i++ is compiler specific.

and i've also heard if..else.. is better than logical if. the post says otherwise. and thinking of it i guess undoing would take more time anyway especially if it is a large operation being done in bar()

Unknown said...

> Note also that
> ++i
> is faster than
> i++
yes, (sometimes - compiler specific) and only if "i" is an object (which has to be copied before i++ operation), not in your example - "i" is just an integer

> Optimize If Statements
How the hell did you invented this?
Compiler works (in assembly) like:
1.test if(~condition)
2.if passed skip {code}, else do nothing so the {code} will be executed

And if you got "else" statement only difference is one relative jump from end of if code to end of else code. One single assembler instruction.