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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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.


  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.

Got any Java Language Question?