Is there a runtime cost for autobox primitive literal?

Let's say I have the following code:

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

Theoretically, true should be autoboxing, which leads to a small effective result compared to the Boolean.TRUE insert. But since we are dealing with a literal value, is it possible for the compiler to replace the primitive literal with the alphabetic alphabetic code so that there is no extra time spent on execution?

Before anyone attacks me, I would choose a primitive literal for the sake of clarity of code, even if there was a small execution cost. This question is mostly theoretical.

+5
source share
1 answer

Yes, there is little success. The valueOf() method of the wrapper type is used to enter the primitive. Since this is such a simple method for Boolean ( return x ? TRUE : FALSE; ), JIT can effectively embed the result; Currently, the Java compiler, however, does not. (Using valueOf() not required by JLS, so optimization for Boolean can be introduced.)

For other types, this is more complicated. For example, Integer returns cached instances for values ​​near zero and creates new instances for large values. Optimization can still be done, but allocating a new instance always takes some time.


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

since we are dealing with a literal value, is it possible for the compiler to replace the primitive literal with an alphabetical booklet

Yes, perhaps, but no, the Oracle javac compiler does not.

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

+4
source

Source: https://habr.com/ru/post/1240206/


All Articles