Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance cost to autobox a primitive literal?

Say I have the following code:

Map<String, Boolean> map = ...
map.put("foo", true);

Theoretically, true will have to be autoboxed, resulting in a slight performance hit versus inserting Boolean.TRUE. But since we're dealing with a literal value, is it possible for the compiler to replace the primitive literal with a boxed literal so there's no extra runtime overhead?

Before anyone attacks me, I would generally opt for the primitive literal for the sake of code clarity, even if there was a tiny performance cost. This question is mostly theoretical.

like image 368
shmosel Avatar asked Sep 26 '22 17:09

shmosel


1 Answers

Yes, there is a small performance hit. In order to box a primitive, the wrapper type's valueOf() method is used. Because this is such a simple method for Boolean (return x ? TRUE : FALSE;), a JIT might be able to effectively inline the result; currently the Java compiler, however, does not. (Use of valueOf() isn't required by the JLS, so an optimization for Boolean could be introduced.)

For other types, it's more complicated. For example, Integer returns cached instances for values near zero, and creates new instances for bigger values. Optimizations can still be performed, but allocating a new instance will always take some time.


In response to comments, let me focus on what I took to be the key point of the question:

since we're dealing with a literal value, is it possible for the compiler to replace the primitive literal with a boxed literal

Yes, it is possible, but no, the Oracle javac compiler does not do this.

Does it matter? No, the performance hit for boxing to Boolean is infinitesimal; boxing boolean using the same valueOf() technique as other primitives is a safe and sane choice for the compiler.

like image 63
erickson Avatar answered Oct 13 '22 00:10

erickson