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.