0

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

Hi, I was asked someday ago that which one is faster variable++ or ++variable? I was little confuse. Can someone tell me which one is faster and why??

Community
  • 1
  • 1
Sarfraz Ahmed
  • 1,349
  • 6
  • 23
  • 43
  • 1
    Check http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c – RageD Apr 11 '11 at 05:02

3 Answers3

1

I think pre-increment would be faster, since it just increments it then and there and the deed is done, whilst post-incrementing requires keeping a copy of said variable a little longer.

This probably depends on the compiler, but I generally use pre-increment unless needed otherwise.

Benjamin
  • 2,718
  • 5
  • 21
  • 20
  • Good compilers generate code that reflects *semantics*, not syntax. If a copy needs to be kept then it will be and if it doesn't then it won't be, regardless of which operator is used. And in most cases, no cppy needs to be kept. – Jim Balter Apr 11 '11 at 06:15
1

In C++ the answer I've personally been given is something along the lines of:

Post increment must create a copy of the objects current state, increment the object, and return the copy by value. For integer types this is irrelevant as by-value returns are the same size and the copy means little.

Pre-increments may simply increment and return itself by reference.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ben
  • 2,867
  • 2
  • 22
  • 32
  • This is not true. A "copy" would only be made if the value prior to post-increment were needed the expression; but in that case the additional cost cannot be attributed to the ++ operator, because the acquisition of that value is needed as a consequence of the entire expression, not as a consequence of the post-increment operator. – kqnr Apr 11 '11 at 05:09
0

There are few answers out there:

http://www.geekinterview.com/question_details/14424
http://www.digitalpeer.com/id/where

but this question is a duplicate

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

---andrew

Community
  • 1
  • 1