What is more efficient, i++ or ++i?

Berek Bryan picture Berek Bryan · Feb 18, 2009 · Viewed 22k times · Source

Exact Duplicate: Is there a performance difference between i++ and ++i in C++?
Exact Duplicate: Difference between i++ and ++i in a loop?


What is more efficient, i++ or ++i?

I have only used this in Java and C/C++, but I am really asking for all languages that this is implemented in.

In college I had a professor show us that ++i was more efficient, but it has been a couple of years, and I would like to get input from the Stack Overflow community.

Answer

Edouard A. picture Edouard A. · Feb 18, 2009

i++ :

  • create a temporary copy of i
  • increment i
  • return the temporary copy

++i :

  • increment i
  • return i

With optimizations on, it is quite possible that the resulting assembly is identical, however ++i is more efficient.

edit : keep in mind that in C++, i may be whatever object that support the prefix and postfix ++ operator. For complex objects, the temporary copy cost is non negligible.