My Java teacher said it was better to use ++n instead of n++, I am not seeing the logic behind this. Does anyone know?
++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.
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.
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