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

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

问题描述

可能的重复:
奇怪的 Java 拳击

最近我看到一个演示文稿,其中包含以下 Java 代码示例:

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

现在我有点困惑.我明白为什么在第一种情况下结果是false"——这是因为 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.

但是为什么在第二种情况下结果是true"?

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.

基本上,Integer 类在 -128 到 127 的范围内保存 Integer 实例的缓存,以及 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.

这是基于这样一个假设,即这些小值比其他整数出现得更频繁,因此避免为每个实例拥有不同对象的开销是有意义的(Integer 对象占用一些东西像 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天全站免登陆