3

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

They say that ++i is faster but I don't understand why.Can anybody show me assembler codes of these operators?

Community
  • 1
  • 1
shift66
  • 11,440
  • 11
  • 47
  • 78
  • See here: http://stackoverflow.com/questions/3346450/c-what-is-the-difference-between-i-and-i/3346729#3346729 – Azodious Nov 10 '11 at 06:42
  • This has been asked many times before, in addition to alread mentioned referenes also http://stackoverflow.com/questions/2020184/preincrement-faster-than-postincrement-in-c-true-if-yes-why-is-it and http://stackoverflow.com/questions/5223950/stl-iterators-prefix-increment-faster. – hlovdal Nov 10 '11 at 06:47
  • For the `int` type there will be no difference whatsoever in most cases. It's just a good habit to always use prefix ++ unless there's a good reason not to, no matter what the type. This is because for some other types prefix ++ can be much, much faster. – Omnifarious Nov 10 '11 at 06:55

2 Answers2

5

++i is definitiely as fast as i++ but it may be faster.
The reason is the implementation.

In order to implement i++ the implementation needs to generate a temporary copy of i unlike the implementation for ++i.

But smart compilers can optimize the genration of this temporary, they certainly do for POD types.

Alok Save
  • 196,531
  • 48
  • 417
  • 525
1

It depends on the compiler and the situation if it generates faster code for this expression.

Nico
  • 1,524
  • 1
  • 23
  • 34