i++ or ++i, any difference?

D

DamonChong

Hi,

Just curious as I'm new to C++ coming from Java background. Is there a
difference in terms of performance if I used i++ instead of ++i in my
codes such as

for(int i=0; i<size; i++)

vs

for(int i=0; i<size; ++i)

I'm under the impression certain compilers like Visual C++ prefers ++i
as it does not create temporaries
(http://www.tantalon.com/pete/cppopt/final.htm).

Thanks in advance for any clarifications!

Regards,
Damon
 
M

Mike Wahler

DamonChong said:
Hi,

Just curious as I'm new to C++ coming from Java background. Is there a
difference in terms of performance if I used i++ instead of ++i in my
codes such as

for(int i=0; i<size; i++)

vs

for(int i=0; i<size; ++i)

Probably not, with a built-in type. If the ++ operators are
members of a user defined type with a 'lengthy' construction
process, then the postfix form could be slower, due to the need
to create a temporary object to save the original value. In any
event, the only way to know for sure is to measure (and this
measurement can easily vary among implementations).
I'm under the impression certain compilers like Visual C++ prefers ++i
as it does not create temporaries
(http://www.tantalon.com/pete/cppopt/final.htm).

I think you're taking the advice at that link out of context.

With a good optimizing compiler (VC++ imo qualifies in this context,
there should be no measurable performance difference between ++i and
i++ with a built-in type.
Thanks in advance for any clarifications!

A final word of advice: Don't worry about such micro-optimizations.
Write your code for clarity and maintainability. Only if you later
can prove that performance is an issue should you consider optimization.
And then, don't try to guess where to do it. Use a profiler.

-Mike
 
M

Marcin Kalicinski

There's absolutely no difference in performance if you use it on int or any
other of the built-in types. There might a difference if you try increment
operator on object of user defined class.

cheers,
Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,055
Members
47,658
Latest member
jaguar32

Latest Threads

Top