Skip to main content
GameDev.net gamedev.net
🔒 Locked

Very Basic Optimisation (pre or post increment)

Started by Nostalgic_Influence Apr 29, 2017 at 8:01 PM 3 replies 2.9k views
Original Post
Nostalgic_Influence
Nostalgic_Influence

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

SiCrane
SiCrane

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.

Khatharr
Khatharr

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.
CrazyCdn
CrazyCdn

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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.