-
September 4th, 2009, 11:31 AM
#1
i++ vs ++i
Hello all.
Just a quick question: I read somewhere that ++i is faster in a for loop than i++.
Why is this the case?
Thanks in advance for the answers.
-
September 4th, 2009, 11:51 AM
#2
Re: i++ vs ++i
i++ increments i and returns the old value of i -> it has to keep the old value somewhere.
Kurt
-
September 4th, 2009, 11:58 AM
#3
Re: i++ vs ++i
For primitives it probably doesn't matter.
For class types, such as STL iterators, there may be an extra copy required for the iter++ form. The compiler may or may not be able to optimize this out, but it doesn't hurt to use the faster form anyway.
-
September 5th, 2009, 09:11 AM
#4
Re: i++ vs ++i
Optimizing compilers make this argument irrelevant.
Besides, if your speed issue is with incrementation, then your the best C/C++ programmer I've ever seen....lol.
norman graham
C++ programmer for 20 years.
-
September 5th, 2009, 10:18 AM
#5
Re: i++ vs ++i
Originally Posted by normbo
Optimizing compilers make this argument irrelevant.
Besides, if your speed issue is with incrementation, then your the best C/C++ programmer I've ever seen....lol.
The point is, when the expressions are standalone, "it doesn't hurt to use the faster form anyway" since there is no other difference to consider (they are both equally readable and require the same amount of effort to type).
-
September 5th, 2009, 12:34 PM
#6
Re: i++ vs ++i
As a good rule of thumb, I always prefer prefix to postfix in C++.
http://www.parashift.com/c++-faq-lit...html#faq-13.15
-
September 5th, 2009, 12:43 PM
#7
Re: i++ vs ++i
Originally Posted by normbo
Optimizing compilers make this argument irrelevant.
No it doesn't. It all depends on the object that is pre/post incremented. Someone could easily write a custom iterator that has post-increment internally doing something that pre-increment doesn't do, and the compiler cannot optimize it away since it would not reflect what the caller really wants to do.
The pre and post increment operations are allowed to have side-effects. In this case, the compiler may not be able to optimize the code, and the programmer is responsible for explicitly calling the correct increment operation.
The only optimization where side-effects are a no-no are the return value optimization (RVO, NRVO), since these optimizations are explicitly specified by the ANSI C++ as perfectly valid, and you shouldn't write code that relies on how many and where copies are being done.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|