Java Language Pitfall - Using 'new' to create primitive wrapper instances is inefficient


Example

The Java language allows you to use new to create instances Integer, Boolean and so on, but it is generally a bad idea. It is better to either use autoboxing (Java 5 and later) or the valueOf method.

 Integer i1 = new Integer(1);      // BAD
 Integer i2 = 2;                   // BEST (autoboxing)
 Integer i3 = Integer.valueOf(3);  // OK

The reason that using new Integer(int) explicitly is a bad idea is that it creates a new object (unless optimized out by JIT compiler). By contrast, when autoboxing or an explicit valueOf call are used, the Java runtime will try to reuse an Integer object from a cache of pre-existing objects. Each time the runtime has a cache "hit", it avoids creating an object. This also saves heap memory and reduces GC overheads caused by object churn.

Notes:

  1. In recent Java implementations, autoboxing is implemented by calling valueOf, and there are caches for Boolean, Byte, Short, Integer, Long and Character.
  2. The caching behavior for the integral types is mandated by the Java Language Specification.