Java中的整数缓存 [英] Integers caching in Java

查看:125
本文介绍了Java中的整数缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

奇怪的Java拳击


最近我看到了一个演示文稿,其中有以下Java代码示例: / p>

Recently I saw a presentation where was the following sample of Java code:

Integer a = 1000, b = 1000;  
System.out.println(a == b); // false  
Integer c = 100, d = 100;  
System.out.println(c == d); // true

现在我有点困惑。我理解为什么在第一种情况下结果是假 - 这是因为Integer是引用类型而且a和b的引用是不同的。

Now I'm a little confused. I understand why in first case the result is "false" - it is because Integer is a reference type and the references of "a" and "b" is different.

但是为什么在第二种情况下结果是真的?

But why in second case the result is "true"?

我听到了一个观点,即JVM将对象的int值从-128缓存到127用于某些优化目的。这样,c和d的引用是相同的。

I've heard an opinion, that JVM caching objects for int values from -128 to 127 for some optimisation purposes. In this way, references of "c" and "d" is the same.

有人可以给我更多关于这种行为的信息吗?我想了解这种优化的目的。在什么情况下性能提高等等。参考一些关于这个问题的研究将会很棒。

Can anybody give me more information about this behavior? I want to understand purposes of this optimization. In what cases performance is increased, etc. Reference to some research of this problem will be great.

推荐答案


我想了解这个
优化的目的。在什么情况下,
的表现会增加等等。
参考这个
问题的一些研究将会很棒。

I want to understand purposes of this optimization. In what cases performance is increased, etc. Reference to some research of this problem will be great.

目的主要是节省内存,由于更好的缓存效率,这也可以带来更快的代码。

The purpose is mainly to save memory, which also leads to faster code due to better cache efficiency.

基本上,整数 class保存整数的缓存,范围为-128到127,以及的所有自动装箱,文字和用法Integer.valueOf()将从该缓存中返回它所覆盖范围的实例。

Basically, the Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.

这是基于这些小值比其他整数更频繁出现的假设,因此避免为每个实例提供不同对象的开销是有意义的( 整数对象占用12个字节。

This is based on the assumption that these small values occur much more often than other ints and therefore it makes sense to avoid the overhead of having different objects for every instance (an Integer object takes up something like 12 bytes).

这篇关于Java中的整数缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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