为什么 Double.valueof javadoc 说它缓存值,但它没有缓存? [英] Why does the Double.valueof javadoc say it caches values, when it doesn't?

查看:45
本文介绍了为什么 Double.valueof javadoc 说它缓存值,但它没有缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 OpenJDK 中,对于方法:

In OpenJDK, for the method:

public static Double valueOf(double d)

javadoc 说:

返回表示指定双精度值的 Double 实例.如果不需要新的 Double 实例,则通常应优先使用此方法而不是构造函数 Double(double),因为此方法通过缓存频繁请求的值可能会显着提高空间和时间性能.

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.

实际代码如下:

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

缓存是谎言!这是怎么回事?

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

推荐答案

该方法存在多种类型:IntegerLongBigDecimal其他和文档总是相同的:在某些情况下(未定义),该方法可以返回相同的结果.

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,缓存仅针对整数类型实现,它返回缓存实例的值介于 -128 和 127(最常见的值)之间.对于 BigDecimal,缓存当前适用于 0 到 10 之间的值.

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.

Java 的更高版本可能将此行为扩展到其他值/更多类型.所以今天使用这段代码是明智的,因为它可能让你明天的代码更快(而且今天的代码不会更慢).

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).

例如,Java 编译器在生成自动装箱代码时使用此 API.

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

这篇关于为什么 Double.valueof javadoc 说它缓存值,但它没有缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆