Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing performance

Why groups j=k*l and m=n*o have different performance, while first 3 groups have 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
}
like image 637
jellyfication Avatar asked Jan 28 '13 08:01

jellyfication


Video Answer


2 Answers

You have a loop which doesn't do anything useful. As such the JIT can take some time to detect this and eliminate the loop. In the first four examples, the code is taking an average of a fraction of a clock cycle. This is a strong hint that the loop has been optimised away and you are actually measuring how long it takes to detect and replace the loop with nothing,

In the later examples, the loop is not optimised away because there is something about the loop which the JIT doesn't eliminate. I suspected it was the object allocation for the Integer but -verbosegc showed that no objects were being created.

On my machine the loop take about 1.9 ns or about 6 clock cycles which is pretty quick so I am not sure what is left which takes that much time..

like image 137
Peter Lawrey Avatar answered Oct 10 '22 23:10

Peter Lawrey


Creating a new object in a cycle always has a cost. In the last two examples you created new Integer objects in the cycle what has high performance cost. Primitives are stored in stack, objects are in heap. Putting something into stack is cheaper than into heap.

like image 45
Donato Szilagyi Avatar answered Oct 10 '22 21:10

Donato Szilagyi