1

I've read recently that ++i is much more efficient in C++ than its counterpart i++ because the first (++i) does the increment and returns the incremented value, whereas the latter (i++) creates a copy of the value, return it and performs an increment.

Does the same happen in Java?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Raul Luna
  • 1,945
  • 1
  • 17
  • 26
  • 1
    *"much more efficient"* is debatable. In most contexts the compiler will optimize them both to the same machine code (when the result is not used). Since postfix and prefix expressions work the same in Java it will presumably behave the same. – UnholySheep May 07 '18 at 08:17
  • whatever performance difference is there it's not going to be more than mere nanoseconds so you shouldn't really care – niceman May 07 '18 at 08:22

1 Answers1

2

Both are not atomic operations composed of the multiple steps. Unlike in C++, these operators can't be overloaded. So there is no difference in Java in the matter of performance.

The only and only difference you should mind between x++ and ++x is that x++ returns the value before it's incremented. And ++x does the same but after the incrementation.

This answer provides a bytecode example.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • But one of the answers [here](https://stackoverflow.com/questions/484462/difference-between-i-and-i-in-a-loop) seems to imply there is a difference in the bytecode. – Tim Biegeleisen May 07 '18 at 08:22
  • Take a look at this answer: https://stackoverflow.com/questions/12396740/is-x-more-efficient-than-x-in-java/12397144#12397144 Better tell us *where* and *why* do you try to save performance. Doubt the `i++` and `++i` will solve anything. Rather think of higher abstraction in Java. If you care this low-level performance, you chose a wrong language. There is no difference in performance in Java. – Nikolas Charalambidis May 07 '18 at 08:31
  • @TimBiegeleisen, the answer you point is for C#, I think it is not entirely useful here – Raul Luna May 07 '18 at 08:54
  • @RaulLuna The answer to which I was referring is for Java. It is entirely useful here. – Tim Biegeleisen May 07 '18 at 09:07