The cost of Autoboxing
Simple question: How expensive is autoboxing of int/Integer types?
Simple answer: 15 nanoseconds per boxing.
No autoboxing ( ints only )
[source:java]
public void runInternalTrial() throws Exception {
int i = getRandomWithoutAutobox();
}
public int getRandomWithoutAutobox() {
return rnd.nextInt(1000);
}
[/source]
Autoboxing
[source:java]
public void runInternalTrial() throws Exception {
int i = getRandom();
}
// Will Autobox an int to an Integer…
public Integer getRandom() {
return rnd.nextInt(1000);
}
[/source]
Note that the Autoboxing example has to Autobox the value returned by getRandom to an Integer and then the caller has to then unbox this back to an int primitive. The two examples for HalfBoxing are simply Autoboxing and then not unboxing back to an int. Here are the results:
![]()















