Java中的整数缓存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3131136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integers caching in Java
提问by Beresta
Possible Duplicate:
Weird Java Boxing
可能的重复:
奇怪的 Java 拳击
Recently I saw a presentation where was the following sample of Java code:
最近我看到一个演示文稿,其中包含以下 Java 代码示例:
Integer a = 1000, b = 1000;
System.out.println(a == b); // false
Integer c = 100, d = 100;
System.out.println(c == d); // true
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.
现在我有点困惑。我理解为什么在第一种情况下结果是“false”——这是因为 Integer 是一种引用类型,而“a”和“b”的引用是不同的。
But why in second case the result is "true"?
但是为什么在第二种情况下结果是“真”?
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.
我听说过一种意见,JVM 缓存对象的 int 值从 -128 到 127 用于某些优化目的。这样,“c”和“d”的引用是相同的。
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.
有人能给我更多关于这种行为的信息吗?我想了解此优化的目的。什么情况下性能提升等等,这个问题的一些研究参考会很大。
采纳答案by Michael Borgwardt
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.
目的主要是为了节省内存,由于更好的缓存效率,这也导致更快的代码。
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.
基本上,Integer
该类Integer
在 -128 到 127 的范围内保留一个实例缓存,并且所有自动装箱、文字和使用Integer.valueOf()
都将从该缓存中返回它涵盖的范围内的实例。
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).
这是基于这样一个假设,即这些小值比其他整数出现的频率要高得多,因此避免为每个实例拥有不同对象的开销是有意义的(一个Integer
对象占用大约 12 个字节)。
回答by dty
Look at the implementation of Integer.valueOf(int)
. It will return the same Integer
object for inputs less than 256
.
看一下实现Integer.valueOf(int)
。Integer
对于小于 的输入,它将返回相同的对象256
。
EDIT:
编辑:
It's actually -128
to +127
by default as noted below.
它实际上是-128
要+127
在默认情况下,如下所述。