Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - Why does the Double.valueof javadoc say it caches values, when it doesn't?

In OpenJDK, for the method:

public static Double valueOf(double d)

The javadoc says:

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

Here's the actual code:

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

The cache is a lie! What's going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The method exists for many types: Integer, Long, BigDecimal and others and the documentation is always the same: Under some circumstances (which aren't defined), the method can return the same result.

AFAIK, the caching is only implemented for integer types and it returns cached instances for values between -128 and 127 (most common values). For BigDecimal, the cache currently works for values from 0 to 10.

Later versions of Java might extend this behavior to other values/more types. So it's smart to use this code today because it might make your code faster tomorrow (and the code won't be slower today).

The Java compiler, for example, uses this API when generating code for autoboxing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...