On 2007-10-16 07:25,
lali.b97@gmail.com wrote:
> Somewhere in a tutorial i read that if statement has performance
> overheads as code within the if statement cannot take benefit of
> pipeling of microprocessor and also that the compiler cannot
> agressively optimize that code.
This is totally off topic:
That is only partially true one a modern PC processor (as opposed to
embedded processors which I have little knowledge about) since they all
have pretty good branch prediction these days. This is best demonstrated
by a simple loop:
for (int i = 0; i < 10; ++i)
{
// do stuff
}
// do other stuff
The processor recognises a loop when it sees one, and it will assume
that you will perform the iterations, so the loop can be optimised very
well. The problem comes when the last iteration is done, since the
processor wrongly assumes that you will iterate you get a small
performance hit when it discovers that you do not.
Similarly the processor can optimise if statements and other control
statements. Even better, they can learn, so if you have an if statement
and you time after time go to the else clause the processor will
remember this and will start executing the else clause when reaching the
if statement before the comparison is complete. Again, should it happen
that the assumption is wrong you get a performance hit.
Notice though that this performance hit is less noticeable on modern
hardware than is was on a P4, since the processors of today are not as
deeply pipelined.
>>From that day onwards i have been trying to avoid if statement withing
> my functions as much as possible and also try to have minimum code
> withing if block.
The best way to optimise an if statement is to write the code that is
most likely to be executed in the if clause and the least likely in the
else clause, since that will save the processor a jump in most cases.
> However, i am bit skeptic about this.
Rightly you should be, you should be sceptic about any optimisation that
is not at the algorithmic level.
> I need some guidance. Performance is always the key issue for me when
> it comes to writing programs.
Select the best algorithms and data structures for the task and then use
a good profiler.
--
Erik Wikström