Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient, i++ or ++i? [duplicate]

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.

like image 470
Berek Bryan Avatar asked Feb 18 '09 15:02

Berek Bryan


People also ask

Is ++ i or i ++ more efficient?

According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."

What is better i ++ or ++ i?

++i is sometimes faster than, and is never slower than, i++. 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.

Which is better i i 1 or i ++ from compilers perspective?

i=i+1 will have to load the value of i , add one to it, and then store the result back to i . In contrast, ++i may simply increment the value using a single assembly instruction, so in theory it could be more efficient.

Why is ++ faster than ++ i?

Why is ++i faster than i++ in C++? I've heard this question come up a few times in C++ programming circles, “Why is ++i faster/better than i++?” The short answer is: i++ has to make a copy of the object and ++i does not. The long answer involves some code examples.


1 Answers

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.

like image 56
Edouard A. Avatar answered Oct 17 '22 23:10

Edouard A.