10

In Java, would there be any performance impact in using post increment vs pre increment operator? (In other languages, a pre-increment can be faster than a post-increment in certain contexts.)

For example, is there a performance difference in these loops?

for (int n = 0; idx < max; ++idx) { /* Note pre-increment */
  f(max);
}

Vs.

for (int n = 0; idx < max; idx++) { /* Note post-increment */
  f(max);
}
erickson
  • 265,237
  • 58
  • 395
  • 493
Jayakumar
  • 101
  • 1
  • 7

2 Answers2

23

A performance question only makes sense in a context where the functional behavior is identical (since, if the functionality is different, a correct behavior is superior to a minutely-faster one), so I'm assuming that you're referring to a situation where the value of the expression is not used? That is, where the only purpose of the expression is to increment i? In such a situation, the answer is no: no performance difference, and in fact, no difference whatsoever. I just compiled this class:

public class Foo
{
    public static void main(final String args[])
    {
        int i = Integer.parseInt(args[0]);
        i++;
    }
}

and computed the MD5 checksum of the resulting Foo.class; and, similarly for a version with ++i instead. They had the same checksum, indicating that the two versions were compiled into the exact same bytecode, and would therefore perform literally identically.

(Naturally, this could, in theory, depend on the compiler. A different compiler might decide to compile i++ differently from ++i even in a context where they're equivalent. But I doubt that, and it's really not worth worrying about even if it the case.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
3

The required runtime for the increment itself ought to be the same, but if you are using a pre- or post-increment obviously may have impact on the performance of the surrounding code and a post-increment can in more situations be optimized away.

There are also some non-obvious cases, where the performance of the surrounding code is changed. At least when run with Oracle's server VM on x86 or x64 hardware, the following loops have a significant difference in their runtime:

long a=0, b=0;
for(int i=0;i<1000000;i++) {
    b = 3;
    a += i * (b++);
}

...

long a=0, b=0;
for(int i=0;i<1000000;i++) {
    b = 3;
    a += i * (++b);
}
jarnbjo
  • 33,923
  • 7
  • 70
  • 94