Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL iterators: Prefix increment faster? [duplicate]

Tags:

c++

stl

Possible Duplicates:
Preincrement faster than postincrement in C++ - true? If yes, why is it?
Is there a performance difference between i++ and ++i in C++?

I got told that when using the STL and it's iterators, I should always use ++iter instead of iter++.

I quote:

Because it can only be faster, never slower

Is this true?

like image 702
dafrad Avatar asked Mar 07 '11 19:03

dafrad


People also ask

Is prefix increment faster?

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 ++ i or ++ faster?

For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.

Is Preincrement faster than Postincrement?

As a result, pre-increment is faster than post-increment because post-increment keeps a copy of the previous value where pre-increment directly adds 1 without copying the previous value.

What is faster i ++ ++ i in C?

In C it is the same. In C++ the faster is ++i; due to its object. However some compilers may optimize the post-increment operator.


1 Answers

Yes. It is true in general. The postfix increment is burdened with the task of preserving and returning the old value of the iterator. That takes time and effort, which is what generally makes it slower.

It is generally true for all overloaded increment/decrement operators that implement the traditional pre/post semantics.

This topic is beaten to death. Do a search here on "prefix postfix" for a large number of more detailed explanations.

like image 60
AnT Avatar answered Sep 28 '22 01:09

AnT