Autoboxing versus manual boxing in Java

Andrei N picture Andrei N · Feb 22, 2010 · Viewed 12.7k times · Source

Why is the second piece of code faster?

Map<Integer, Double> map = new HashMap<Integer, Double>();
for (int i = 0; i < 50000; i++) {
    for (double j = 0.0; j < 10000; j++) {
        map.put(i, j);
    }
}

Map<Integer, Double> map=new HashMap<Integer, Double>();
for (int i = 0; i < 50000; i++) {
    for (double j = 0.0; j < 10000; j++) {            
        map.put(new Integer(i), new Double(j));
    }
}

Answer

Esko Luontola picture Esko Luontola · Feb 22, 2010

Autoboxing uses Integer.valueOf, which internally caches Integer objects for small integers (by default -128 to 127, but the max value can be configured with the "java.lang.Integer.IntegerCache.high" property - see the source code of Integer.valueOf), so it is different from calling new Integer directly. Because Integer.valueOf does a quick check for the magnitude of the integer value before calling new Integer, it's a little bit faster to call new Integer directly (though it uses more memory if you have lots of small integers). Allocation in Java is very fast, and the time doing GC is proportional to the number of live short-lived objects (i.e. not proportional to the amount of garbage), so GC is also very fast.

But depending on the JVM version and which optimizations are enabled, there is the scalar replacement optimization, which can in produce a much bigger performance difference when allocating short-lived objects (in your example that optimization can't be done, because you are storing the objects in a map, but in many other situations it's useful).

In recent JVM versions there is scalar replacement optimization (except in 1.6.0_18 where escape analysis is temporarily disabled), which means that allocations of short-lived objects can be optimized away. When scalar replacement in JVM was new, somebody made a benchmark where there was code similar to yours. The result was that the code which used primitives was fastest, the code with explicit new Integer() calls was nearly as fast as the one using primitives, and the code which used autoboxing was much slower. This was because autoboxing uses Integer.valueOf and at least back then scalar replacement optimization did not take that special case into consideration. I don't know whether the optimization has been improved since then.