Auto Boxing vs static numbers
Asked Answered
E

2

5

Is it valuable for using Integer i = NumberUtils.INTEGER_ONE instead of Integer i = 1? I don't know what happen behind auto boxing.

Thanks

Esophagitis answered 1/8, 2011 at 9:13 Comment(3)
Like many optimisations, you should first ask; what is the simplest and clearest way to write this? Do you need an Integer or would an int be simpler?Brackett
@PeterLawrey: Yes, I need an Integer and your "questions" are what I wanted to asks. Thanks for the clarification :-)Esophagitis
My answer would be int i = 1; is simplest, clearest and fastest.Brackett
R
10

Basically it will be compiled into:

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

assuming INTEGER_ONE is declared as an int.

At execution time, assuming INTEGER_ONE has the value 1, that will actually return a reference to the same object each time, guaranteed by the Java Language Specification, because it's in the range -128 to 127. Values outside that range can return references to the same object, but don't have to.

Rhinelandpalatinate answered 1/8, 2011 at 9:14 Comment(0)
E
1

Many wrappers and utility classes in java have cached pools. Integer uses an internally cached static array of 'Integer' references to dish out when the valueOf() method is invoked. Strings also have a similar pool.

If however you do something like Integer i = 128, that will begin to impact performance since autoboxing will kick in for uncached integers (Not that it does not kick in for cached integers). Unlike the case where cached integers were returned, this statement creates a new object. Object creation is expensive and drags down performance.

[EDIT]

Clarified answer

Ensile answered 1/8, 2011 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.