Difference in performance between post and pre-increment operators?

In Java, will there be any performance impact when using the post-increment or pre-incremental operator? (In other languages, pre-zooms may be faster than subsequent zooms in certain contexts.)

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

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); } 
+7
source share
2 answers

The performance question only makes sense in a context where the functional behavior is identical (because if the functionality is different, the correct behavior is superior to the minimally fast), so I assume that you are referring to a situation where the value of the expression is not used? That is, where the sole purpose of the expression is to increase i ? In this situation, the answer is no: there is no difference in performance, and in fact there is no difference at all. I just compiled this class:

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

and calculated the MD5 checksum of the received Foo.class ; and similarly for c ++i version. They had the same checksum, indicating that the two versions were compiled into the same bytecode and therefore would execute literally the same way.

(Naturally, this could theoretically depend on the compiler. Another compiler may decide to compile i++ differently from ++i even in the context where they are equivalent. But I doubt it, and it really should not be worried, even if it is.)

+21
source

The required execution time for the increment itself should be the same, but if you use a preliminary or post-increment, it can obviously affect the performance of the surrounding code, and the post-increment can be more optimized away.

There are also some non-obvious cases where the performance of the surrounding code changes. At least when working with the Oracle server VM on x86 or x64 hardware, the following cycles have a significant difference in their execution time:

 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); } 
+2
source

Source: https://habr.com/ru/post/1402266/


All Articles