Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between n++ VS ++n in Java

Tags:

java

My Java teacher said it was better to use ++n instead of n++, I am not seeing the logic behind this. Does anyone know?

like image 208
Mohammad Avatar asked Jan 20 '11 21:01

Mohammad


2 Answers

++n increments the value and returns the new one.

n++ increments the value and returns the old one.

Thus, n++ requires extra storage, as it has to keep track of the old value so it can return it after doing the increment.

I would expect the actual difference between these two to be negligible these days. I know a lot of compilers will optimize it so they're identical if the return of n++ isn't actually used, though I don't know of Java does that.

like image 66
Herms Avatar answered Oct 05 '22 09:10

Herms


Your Java teacher is (probably) refering to the fact that preincrementation is usually a little tiny bit faster than postincrementation. I'm not even sure if that's the case in Java, because I learned about that in C course.

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

Donald Knuth

In everyday pracitice, I would use pre- or postincrementation basing mainly on what makes the most sense in the code.

like image 34
Mchl Avatar answered Oct 05 '22 07:10

Mchl