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