-2

Why is ++i 1ms faster than i++? What's going on in the background in memory.

Results:

i++ : 3ms

++i : 2ms

Here's the method I used to test.

    int TERM = Integer.MAX_VALUE;

    long startTime = System.currentTimeMillis();

    for(int i = 0; i < TERM;)
    {
        i++;
        // ++i;
    }

    long endTime = System.currentTimeMillis();

    System.out.println(endTime - startTime);
  • 2
    http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Oliver Charlesworth Sep 01 '16 at 22:04
  • 1
    Why do you assume, that your "benchmark" is correct and produces viable results? – Tom Sep 01 '16 at 22:06
  • Gernally speaking `++i` (preincrment) is easier to optimize than `i++` (postincrement), because since postincrement becomes effective only after evaluating the expression, you have to keep the original value before the increment was applied around longer. Maybe this applies here in some way, but you will have to look at the bytecode and how the JVM does things. – mschwaig Sep 01 '16 at 22:12
  • 2
    Once compiled, the optimizer will very probably remove the loop and replace by a single assignment. Both version will produce exactly the same code. Variations are too small to be significant, if measured by currentTimeMillis – Fabien Benoit-Koch Sep 01 '16 at 22:13
  • Yeah, no. Just stop. These will get compiled down to the same thing; any variation is due to how you're measuring, or to cosmic randomness. – Louis Wasserman Sep 01 '16 at 22:37

1 Answers1

-1

You cannot think in terms of this level in java as JIT would wrap your code at machine level unintelligently.

If you write ++i or i++, it will be converted to byte code to exact same instruction set.

Bytecode for both of these is :

Code:
       0: iconst_0      
       1: istore_1      
       2: iload_1       
       3: iload_0       
       4: if_icmpge     13
       7: iinc          1, 1
      10: goto          2
      13: return
Rishi
  • 1,163
  • 7
  • 12