34

Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?

I am writing a program where an iterator is used to loop through a std::vector. Somebody told me that doing ++it in the for statement leads to more efficient code. In other words, they are saying that:

for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); ++it )

runs faster than

for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); it++ )

Is this true? If it is, what is the reason behind the efficiency improvement? All it++/++it does is move the iterator to the next item in the vector, isn't it?

Ajay
  • 18,086
  • 12
  • 59
  • 105
  • 7
    See: http://stackoverflow.com/questions/24901/ – Shog9 Jul 02 '09 at 22:48
  • 2
    An exact duplicate, but rep race is on anyway. – macbirdie Jul 02 '09 at 22:52
  • 1
    This is about iterators, and so should the answers. The other questions seems to ask about the overall difference. I think they are related questions, but not exact duplicates? – Johannes Schaub - litb Jul 02 '09 at 22:55
  • 1
    @litb: tough call... The other question is asking for C++-specific performance differences between the two operators, and the answers reflect this in discussing how object implementation can potentially result in such discrepancies. Iterators are (or can be) objects; so this is really a subset of the previous question. – Shog9 Jul 02 '09 at 23:00
  • Yes, that's what i pointed out :) No exact duplicate, but rather a specialized version of the other. this thread, we may delve into iterator validity, whereas in the other, that would just be too specific. At some point, any topic is a subset of the "tell me how to program" question :) – Johannes Schaub - litb Jul 02 '09 at 23:11
  • Unfortunately, most of the answers to not appear to be taking advantage of this specificity. Ah, well... I'll upvote the ones that do. ;-) – Shog9 Jul 02 '09 at 23:17
  • 1
    That said, i agree with you, there doesn't seem to be a difference when he's only asking about efficiency. Looks like a dupe! :) – Johannes Schaub - litb Jul 02 '09 at 23:21
  • Closely related to these other questions: * [http://stackoverflow.com/questions/561588/what-is-more-efficient-i-or-i-closed](http://stackoverflow.com/questions/561588/what-is-more-efficient-i-or-i-closed) * [http://stackoverflow.com/questions/24901/](http://stackoverflow.com/questions/24901/) * [http://stackoverflow.com/questions/484462/](http://stackoverflow.com/questions/484462/) – abelenky Jul 02 '09 at 22:47
  • Article: Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for iterators? - https://www.viva64.com/en/b/0093/ – AndreyKarpov Aug 18 '17 at 14:02

7 Answers7

43

The reason behind the preincrement being faster is that post-increment has to make a copy of the old value to return. As GotW #2 put it, "Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int."

GotW #55 provides the canonical form of postincrement, which shows that it has to do preincrement plus some more work:

T T::operator++(int)
{
  T old( *this ); // remember our original value
  ++*this;        // always implement postincrement
                  //  in terms of preincrement
  return old;     // return our original value
}

As others have noted, it's possible for some compiler to optimize this away in some cases, but if you're not using the return value it's a good idea not to rely on this optimization. Also, the performance difference is likely to be very small for types which have trivial copy constructors, though I think using preincrement is a good habit in C++.

aem
  • 3,896
  • 24
  • 20
  • 4
    Note that decent compilers will optimize away the copy of the old value if it never gets used. – Phil Miller Jul 02 '09 at 22:47
  • 2
    Exactly: you can't promise that preincrement is more efficient than postincrement, because (a) the standard does not require it, and (b) it's pretty easy to invent combinations of source code and compiler where the two are equally efficient. – Steve Jessop Jul 02 '09 at 22:49
  • But you can assume that preincrement is at least as efficient as postincrement. So why not just always use it, when they are otherwise equivalent? – Nick Lewis Jul 02 '09 at 22:54
  • 2
    Agreed: I think use preincrement where possible, since I can't think of a legitimate reason for it to be worse than post. If some class overloads both operators (badly) and somehow makes preincrement worse, then the caller can't be blamed for failing to work around it. I just don't think one should promise that it is "more efficient" (which many will read as "strictly more efficient"), when there is no such guarantee, and indeed typically they're identical in optimised code. – Steve Jessop Jul 02 '09 at 23:02
10

It's unlikely to make any difference for a vector.

In general, ++it is extremely unlikely to be slower than it++ (assuming a sensible implementation, if they're overloaded), and just might be faster. The reason is that if the iterator class itself is at all complex, then because it++ has to return the value before it is incremented, the implementation will generally make a copy.

Vector iterators are probably "just pointers" (in optimised, non-debug builds), and both operator++s will be inlined. Since the return value is unused the copy will typically be elided. So it won't make any difference. I'm in the habit of typing ++it because:

1) Some day it might make a difference, for some iterator type, and I don't want to have to do something special for that type.

2) Personally I think the prefix operator more clearly expresses the intent: "increment it", as opposed to "use it and then increment".

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • I'd have to say number 2 for me was more confusing to see ++it than it++. For example, looking at a regular int for loop, for (int i = 0; i <10; i++) tells me I have the integer i that I set to 0 (on purpose because I want it 0 the first time), I want to do this as long as i is less than 10, and I want to increment i by ONE each time after the loop is done). so to see ++it was very confusing for me the first time, I remember thinking (why would u want to iterate BEFORE doing something? why wouldn't you just set it to what you want instead of 1 less than what u want?). I get it now but still – Josh Aug 15 '17 at 19:39
  • @Josh: well OK, but that's just a consequence of the newcomer's utter confusion as to when the last part of the for loop executes. Of course you still initialise to 0, and it still has value 0 the first time through the loop, 1 the second time, etc, regardless of whether you write `++i` or `i++`. Frankly, if writing `++i` prompts the newcomer to resolve that confusion sooner rather than later, and understand that the clause is executed *after* the body of the loop no matter what's in it, then I'd rate it as an additional advantage for `++i`! – Steve Jessop Aug 18 '17 at 09:09
  • I guess I should chalk to up to bad teachers back in high school before I went off to college. They told us ++i meant it would increment before evaluating what's inside the loop, and i++ would increment after evaluation of what's inside the loop. If I had been told correctly from the beginning, the confusion would have never existed. – Josh Aug 18 '17 at 20:46
7

it++ performs the following operations:

  1. create a copy of it
  2. increment it
  3. return the original (non-incremented) it

++it performs the following operations:

  1. increment it
  2. return it

Because it++ creates a copy, it can be said to be "slower". However, any decent compiler will optimize this difference out for most defined types. For some user-defined types it can be faster.

Ajay
  • 18,086
  • 12
  • 59
  • 105
thekidder
  • 3,486
  • 1
  • 33
  • 36
4

Sometimes yes. With some it will be optimized away and be the same. For std::vector<> (and other std-iterators) it will most likely be optimized to be the same.

Thomas
  • 4,208
  • 2
  • 29
  • 31
3

There is a chance that it++ will create a temporary copy.

Also, in C++, there is a chance that someone has overloaded the postincrement operator.

Both of these things could decrease performance vs preincrement. Neither is likely to matter in practice. The temporary copy, in particular, will be optimized away by most compilers since there are no side effects in the 3rd expression of your For loop.

Richard Berg
  • 20,629
  • 2
  • 66
  • 86
2

yes ++it is more efficient because it++ need to return a copy of the object then increment itself.

oscarkuo
  • 10,431
  • 6
  • 49
  • 62
1

Yes. As far as I remember, ++it is more efficient than it++, because it++ creates a temporary object, while ++it does not.

Stefano Borini
  • 138,652
  • 96
  • 297
  • 431