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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With