This method is likely to yield significantly better performance

This week, I came across an interesting difference between the Java API documentation and its current implementation. A difference? Or is it just a matter of thorough reading?

If you look at the Javadoc for Double.valueOf(), you’ll find that it is likely to outperform the use of new Double(). Sounds good! And don’t we all ove it when we get a free performance boost?

However, examining the source code to see what causes this “significantly better space and time performance”, we find….

public static Double valueOf(double d) {
    return new Double(d);

Well, that’s a bit of a disappointment… no caching of frequently used values, as the Javadoc suggests. Just the same as we would’ve done either way when there was no valueOf() method. Now let’s see whether the promised performance gain for Integers is also non-existing.

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);

Well, that looks more like it! Indeed, there’s an private static class IntegerCache inside the Integer class, with an array of Integer objects that gets initialised upon first usage. By default, it contains all Integers from -128 and 127 (inclusive), but you can even change the upper limit of the cache by specyfing the java.lang.Integer.IntegerCache.high property.