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 adds one to n, then uses it; n++ uses it then adds one. Same applies to --.
++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.
They do different things.
Let's say n = 10. Then n++ increments n but returns 10.
++n increments n and returns 11.
Though I'm not sure which one requires more assembly instructions.
Interesting example that illustrates the difference:
public class Main {
public static void main(String[] args) {
for (int i=0; i<5; /*not incrementing here*/ )
System.out.println(i++);
}
}
output: 0 1 2 3 4
public class Main {
public static void main(String[] args) {
for (int i=0; i<5; /*not incrementing here*/ )
System.out.println(++i);
}
}
output: 1 2 3 4 5
Notice that neither for-loop performs the incrementation since it does not matter there.
n++ will increment the variable prior to the operation taking place, while ++n only increments the variable after the operation.
So take x = 1
y = x++
y = 1
x = 2 now
So take x = 1 again
y = ++x
y = 2
x = 2 now