Auto Boxing Performance

Why do groups j=k*land m=n*ohave different performance, while the first 3 groups are the same?

int a = 42;
int b = 42;
int c = 42;

Integer d = 42;
int e = 42;
int f = 42;

int g = 42;
Integer h = 42;
int i = 42;

int j = 42;
int k = 42;
Integer l = 42;

Integer m = 42;
Integer n = 42;
Integer o = 42;

for(int z = 0; z < 1000000000; z++){
    // c = a*b; // 630 ms
    // f = d*e; // 630 ms
    // i = g*h; // 630 ms
    // l = j*k; // 6000 ms
    // o = m*n; // 6400 ms
}
+5
source share
7 answers

You have a loop that does nothing useful. Thus, the JIT may take some time to detect this and eliminate the loop. In the first four examples, the code takes on average a fraction of the clock cycle. This is a strong hint that the cycle has been optimized, and you actually measure how long it takes to find and replace the cycle with nothing,

, - , JIT . , Integer, -verbosegc , .

1,9 6 , , , , .

+6

. Integer , . , . - , .

+4

, JVM, .

c = a*b; // 630  ms -> No boxing and unboxing
f = d*e; // 630  ms -> Unboxing d
i = g*h; // 630  ms -> Unboxing h
l = j*k; // 6000 ms -> Creates a new Integer object L, and assign J * K to L
o = m*n; // 6400 ms -> Creates a new Integer object 0, unbox m and n for calculation and assign m * n to o

l = j * k;//6000

temp = j*k;
Integer l = new Integer(temp); 

o = m * n;//6400

temp = j.intValue() * k.intValue();
Integer l = new Integer(temp); 

1000000000 ( count) Integer. , , .

+4

, l = j * k int Integer, c = a * b . VM , , , 1 . -.

0
m = n*o  ==> Integer = Integer * Integer 

l = j*k ==> Integer = int * int // Integer is an object so autoboxing costs some performance here.
0
  • Integer autobox

: java.lang.Integer.IntegerCache

0

Creating an object has overhead (or, according to other comments, it seems that when creating an object, the cycle cannot be optimized, because nothing is done inside it).

int = int * int

No objects.

int = Integer * int or int = int * Integer

The Integer int member is multiplied by int, and no objects need to be created.

Integer = int * int

An Integer object must be created from the result (slow).

Integer = Integer * Integer

The two Integer int elements are multiplied, but then the Integer object must be created from the result (slow).

0
source

All Articles