0

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);
Ensom Hodder
  • 1,522
  • 5
  • 18
  • 35
  • possible duplicate of [Which is better in terms of performance, implicit (auto) unboxing or explicit unboxing?](http://stackoverflow.com/questions/6915823/which-is-better-in-terms-of-performance-implicit-auto-unboxing-or-explicit-un) – isaias-b Sep 26 '15 at 20:36
  • 2
    "if performance is critical" it may depend on task you are running. `Integer i = 5;` thanks to autoboxing is same as `Integer i = Integer.valueOf(5);` which thanks to internal caching of integers in range `-128,127` will let you reuse these instances of `Integer` class so you will use less space. But if you don't care about space then `new Integer(5)` may be faster because you will skip searching for cached ints. – Pshemo Sep 26 '15 at 20:38
  • 1
    possible duplicate of [New Integer vs valueOf](http://stackoverflow.com/questions/2974561/new-integer-vs-valueof) – sstan Sep 26 '15 at 20:38

1 Answers1

5

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.

Community
  • 1
  • 1
sstan
  • 35,425
  • 6
  • 48
  • 66