为什么Integer仅在Java中小于128(默认值)的情况下充当实习生 [英] Why Integers act as interns only for the values less than 128 (default) in java

查看:137
本文介绍了为什么Integer仅在Java中小于128(默认值)的情况下充当实习生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对于小于128(默认值)的值,而不是大于该值的值,Integers就像实习生一样.我知道已经多次回答了这个问题,但是我没注意到有人问原因.

I know that Integers act like interns for the values less than 128 (default) and not for the values more than that. I know that this has been given as an answer many times but I couldn't noticed a place that the reason is asked.

那么我想知道的是,为什么整数仅对小于128(默认值)的值而不对大于该值的值充当实习生?如何改善较少的内存使用/高性能?

So what I want to know is Why Integers act as interns only for the values less than 128 (default) and not for the values more than that? How does it improve the less memory usage / high performance?

推荐答案

技术上,在加载类时会预先缓存值.不同于String.intern()可以返回您创建的值.

Technically the values are pre-cached when the class is loaded. It is not like String.intern() where a value you created can be returned.

最大值也可能不是127,如果您设置为最大值或使用-XX:+AggressiveOpts

Also the maximum might not be 127, it can be higher if you set it so or use options like -XX:+AggressiveOpts

可能选择默认范围只是为了与字节保持一致.注意:缓存的值是

The default range is likely to be chosen just to be consistent with Byte. Note: the cached values are

Boolean: both values
Byte: all
Character: 0 to 127
Short: -128 to 127
Integer: -128 to 127
Long: -128 to 127
Float and Double: none
BigInteger: -16 to 16 (in HotSpot Java 7)
BigDecimal: 0 to 10 (if you use valueOf(long)) and 
            0 to 0.000000000000000 (if you use valueOf(long, int)) (in HotSpot Java 7)

这样做的原因是为了提高性能并降低GC压力.

The reason it is done is to improve performance and reduce GC pressure.

创建垃圾可以使缓存中充满垃圾,从而减慢所有代码的速度,还需要创建对象并清理它们.您所做的工作越少,程序就会变得更快,更一致.

Creating garbage can fill your cache with garbage, slowing down all your code, it also takes work to create objects and to clean them up. The less work you do the faster and more consistent your program will be.

这是一篇很好的文章,说明了与众不同之处 http://www.javaspecialists.eu/archive/Issue191.html

Here is a good article of the difference it makes http://www.javaspecialists.eu/archive/Issue191.html

这篇关于为什么Integer仅在Java中小于128(默认值)的情况下充当实习生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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