Auto Boxing Against Static Numbers

Is it useful to use Integer i = NumberUtils.INTEGER_ONE instead of Integer i = 1 ? I do not know what is happening behind the auto box.

thanks

+4
source share
2 answers

It will mainly be compiled into:

 Integer i = Integer.valueOf(NumberUtils.INTEGER_ONE); 

Assuming INTEGER_ONE declared as int .

At run time, if INTEGER_ONE is 1, it will actually return a reference to the same object every time, guaranteed by the Java language specification, because it is in the range from -128 to 127. Values ​​outside this range can return references to one the same object, but not necessary.

+9
source

Many shells and utility classes in java have cached pools. Integer uses the built-in cached static array of integer references to flush when the valueOf () method is called. Lines also have a similar pool.

If, however, you do something like Integer i = 128, which will begin to affect performance, since autoboxing will be used for non-integer integers (not what it does not use for cached integers). Unlike the case when cached integers were returned, this statement creates a new object. Creating objects is expensive and reduces productivity.

[EDIT]

Refined Answer

0
source

All Articles