Very Basic Optimisation (pre or post increment)

Started by
3 comments, last by CrazyCdn 6 years, 11 months ago

Hi, probably a very stupid question but anyway:

My lecturer told me that this "++i" is faster than "i++" when incrementing a for loop. Can anybody argue this point?

And if it's true, could you possibly explain why it's faster?

Cheers

Advertisement

It depends on the type of i. If i is an integer, your compiler will likely generate the exact same code either way. If i is a complex type like an iterator with range checking, then ++i may be faster. Basically, ++i just increments i. i++ requires a copy to be made of i and then the object is incremented before returning the old copy. For integers, its very easy for the compiler to realize that the copy doesn't matter. For complex type it may or may not be able to decide that.

I've noticed that the VS compiler tends to be more aggressive about eliding the copy when it's the "iterate" argument of a for loop. I don't remember what version it was that I was looking at, though.

It's not a bad habit to just use the prefix operator when you're not capturing the result, though.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

Brilliant. Thanks very much!

I've never seen a case where ++i was slower than i++. At worst case they're equal. So until I see otherwise in a profiler I always use ++i.

"Those who would give up essential liberty to purchase a little temporary safety deserve neither liberty nor safety." --Benjamin Franklin

This topic is closed to new replies.

Advertisement