【BASE】Integer 缓存

在 Java 中,Integer 缓存(Integer Cache)是 Java 为了优化小整数对象的创建和使用而引入的机制。它的核心作用是减少 Integer 对象的创建,提高性能和减少内存消耗。

Integer 缓存机制

  • 范围:默认缓存 -128127 之间的整数。
  • 原理:对于这个范围内的整数,Integer.valueOf(int) 方法不会新建对象,而是返回缓存池中的对象。
  • 触发条件
    • 使用 Integer.valueOf(int) 方法创建 Integer 对象时,会复用缓存池对象。
    • 自动装箱(Autoboxing)时,实际上调用的是 Integer.valueOf(int),也会使用缓存池。

示例代码

public class IntegerCacheTest {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        System.out.println(a == b); // true,引用相同,来自缓存

        Integer c = 128;
        Integer d = 128;
        System.out.println(c == d); // false,超出缓存范围,创建新对象
    }
}

解释

  • a == b 结果是 true,因为 127Integer 缓存范围内,ab 指向同一个对象。
  • c == d 结果是 false,因为 128 超出了默认缓存范围,Integer.valueOf(128) 会创建新的 Integer 对象。

Integer 缓存的实现

查看 Integer 类的 valueOf(int) 方法:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
  • IntegerCache.low = -128IntegerCache.high = 127(默认)。
  • IntegerCache.cache 是一个数组,存储 -128127 之间的 Integer 实例。
  • 如果 i 在缓存范围内,直接返回 cache 数组中的对象,否则新建一个 Integer 对象。

如何修改缓存范围

可以通过 -XX:AutoBoxCacheMax=<N> JVM 参数调整最大缓存值。例如:

java -XX:AutoBoxCacheMax=200 IntegerCacheTest

这样 Integer.valueOf(200) 也会被缓存。

为什么需要缓存?

  • 避免频繁创建小整数对象,减少 GC(垃圾回收)压力。
  • 提高整数运算的效率,尤其是在大量使用小整数的场景(如循环、计数、索引)。

注意点

  1. new Integer(x) 不会使用缓存

    Integer x = new Integer(127);
    Integer y = new Integer(127);
    System.out.println(x == y); // false
    
    • new 关键字会创建新对象,不会使用缓存。
  2. 其他包装类也有类似缓存

    • ByteShortLongCharacter(0-127)、Boolean 也有类似的缓存。
    • FloatDouble 没有缓存机制。

总结

  • Integer 默认缓存 -128127 的整数。
  • Integer.valueOf(int) 复用缓存,new Integer() 不使用缓存。
  • 可以通过 -XX:AutoBoxCacheMax=N 调整缓存上限。
  • 适用于 ByteShortLongCharacter(0-127)和 Boolean,但 FloatDouble 没有缓存。

这个缓存机制是 Java 提升性能、减少内存消耗的重要优化手段,特别是在数值计算和集合操作中非常有用。

posted on   滚动的蛋  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示