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.
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."
++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.
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 ++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.
i++ :
++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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With