Search code examples
javaautoboxing

To what extent are cached instances used for common Float and Double values?


For Integer and some other numeric types, instances representing values in the range -128 to 127 are re-used when calling valueOf or autoboxing a primitive value.

But what about Float and Double? The javadoc for valueOf hints that it may likewise use cached values:

If a new Float instance is not required, this method should generally be used in preference to the constructor Float(float), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

However, this statement is less definitive when compared to Integer's valueOf ("This method will always cache values in the range..."), and does not state a set of values for which this optimization might be in place. So how does this actually behave in practice?


Solution

  • Looking into the implementation of Float.valueOf (JDK 8), I see that it just creates a new Float object by calling the constructor.

    public static Float valueOf(float f) {
        return new Float(f);
    }
    

    So, it maybe an optimization for the future.