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

后端 未结 7 2012
醉酒成梦
醉酒成梦 2021-01-01 03:56

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

相关标签:
7条回答
  • 2021-01-01 04:24

    ++n adds one to n, then uses it; n++ uses it then adds one. Same applies to --.

    0 讨论(0)
  • 2021-01-01 04:26

    ++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.

    0 讨论(0)
  • 2021-01-01 04:32

    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.

    0 讨论(0)
  • 2021-01-01 04:34

    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.

    0 讨论(0)
  • 2021-01-01 04:41

    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.

    0 讨论(0)
  • 2021-01-01 04:44

    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
    
    0 讨论(0)
提交回复
热议问题