Reputation: 1548
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
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 constructorInteger(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
to127
, 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