Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preincrement faster than postincrement in C++ - true? If yes, why is it? [duplicate]

Tags:

c++

People also ask

Why Preincrement operator is faster than Postincrement?

Pre-increment is faster than post-increment because post increment keeps a copy of previous (existing) value and adds 1 in the existing value while pre-increment is simply adds 1 without keeping the existing value.

Is Preincrement faster?

actually - it depends. Postincrement needs a copy since it preserves the old value. If the type incremented is a complex type (e.g. an iterator) and not a simple type, the preincrement is faster than the postincrement. That is only true of course if you don't need the value before the increment.

What is the difference between Preincrement and Postincrement in C?

Pre-increment and Post-increment concept in C/C++?Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.


Post-increment usually involves keeping a copy of the previous value around and adds a little extra code. Pre-increment simply does it's job and gets out of the way. I typically pre-increment unless the semantics would change and post-increment is actually necessary.


On any decent compiler, ++i and i++ are identical if the value is not used.

If the value is used, ++i would need a temporary to store the pre-increment value if identical semantics were wanted.


Postincrements have to make a copy of the object to return the unincremented value. For class types, this could be significant but for "int-like" types (incl. pointers), it's probably not.


The difference for plain types types such as int is probably negligible. I would guess the compiler is able to optimize such cases (e.g. turn a postfix into a prefix increment where appropriate). However, for complex types (typically STL iterators the difference might be noticeable). The compiler is not able to switch to prefix in these cases because the operators actually might do totally different things. I recommend reading STL Iterators and Performance for some background info on the performance penalty on using post-increment for STL iterators(short story: it takes twice the time as the pre-increment).