post vs. pre incrementation

  • Thread starter Thread starter Michael B.
  • Start date Start date
M

Michael B.

Hi!

I have a very simple question: Is it still true that pre variable
incrementation (like ++i) is faster than post incrementation (i++). I heard
that in modern compilers it makes no difference as the both versions are
optimised to one type of code. I've also never encountered any performance
difference in using e.g.

for(i=0; i < n; ++i) statement;

over

for(i=0; i < n; i++) statement;

However, nearly every methodology suggest using the first case.

Could you explain me why it is so, and if it makes any difference for VC++
or VC.NET?

Regards,

Michael
 
It doesn't for integers. It can for more complex types because for these you
need to make a copy in the post-increment case and you don't need to in the
pre-increment case. Looking at the generated code for a more complex type
like a non pointer iterator should illustrate the difference.

Ronald Laeremans
Visual C++ team
 
Michael B. said:
[...] I've also never encountered any performance
difference in using e.g.

for(i=0; i < n; ++i) statement;

over

for(i=0; i < n; i++) statement;

Which types did you test this with?
I would expect this to be cured by
the optimizer.
However, nearly every methodology suggest using the first case.

Could you explain me why it is so, and if it makes any difference for VC++
or VC.NET?

Here is a canonical implementation for
the two for a user-defined type 'T':

T& operator++() {inc();return *this;}
T operator++(int) {T tmp(*this);inc();return tmp;}

You see that the postfix version calls
the copy ctor two times. It depends on
the actual code whether the optimizer
can remove this.
This is why I would recommend you always
do what you want: If you need the old
value, use postfix increment(/decrement).
Otherwise, use the prefix one.
Regards,

Michael

Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
 
Back
Top