Ensom Hodder
Ensom Hodder

Reputation: 1548

what is the best way to create primitive wrapper class in Java

I know in Java, there are three different ways below to transform the primitive types to their corresponding wrapper classes. However, is there any preferred way if performance is critical ?

Integer i = new Integer(5);
Integer i = 5;
Integer i = Integer.valueOf(5);

Upvotes: 0

Views: 527

Answers (1)

sstan
sstan

Reputation: 36483

The javadocs for Integer.valueOf(int) emit a pretty clear recommendation:

If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

And as pointed out by Pshemo in the comments, and as considered in this SO thread, Integer i = 5; essentially gets converted automatically to Integer i = Integer.valueOf(5);. So using either won't make a difference performance-wise.

So if performance is a concern, simply avoid using new Integer(5) to benefit from the caching.

Upvotes: 5

Related Questions