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 reused with a valueOf or autoboxing call to a primitive value.

But what about Float and Double? javadoc for valueOf suggests that it can also use cached values:

If a new instance of Float is not required, this method should generally be used instead of the Float constructor, since this method is likely to provide significantly better performance in space and time by caching frequently requested values.

However, this operator is less defined than IntegerOf ("This method will always cache values ​​in the range ...") and does not set the set of values ​​for which this optimization can be set. So how does this actually behave in practice?

+4
source share
2 answers

Looking at the implementation Float.valueOf(JDK 8), I see that it simply creates a new Float object, invoking the constructor.

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

So, it could be optimization for the future.

+2
source

While Javadoc says caching can be used, I just checked the implementation in my JDK (version 8), and caching is not implemented:

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

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

, . Integer, Long, Byte, Short Character ( ), , Double Float .

+2

Source: https://habr.com/ru/post/1694111/


All Articles