Jump to content
  • Advertisement
Sign in to follow this  
Nostalgic_Influence

Very Basic Optimisation (pre or post increment)

This topic is 590 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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. 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!