Integer缓存策略

这篇文章其实是讲Java和Python的,其他的语言并不知道。

在Java里你可能会遇到这样一个问题:

public class JavaIntegerCache {
    public static void main(String... strings) {

        Integer integer1 = 3;
        Integer integer2 = 3;

        if (integer1 == integer2)
            System.out.println("integer1 == integer2");
        else
            System.out.println("integer1 != integer2");

        Integer integer3 = 300;
        Integer integer4 = 300;

        if (integer3 == integer4)
            System.out.println("integer3 == integer4");
        else
            System.out.println("integer3 != integer4");

    }
}

那么问题来了,答案是什么,首先,我们应该比较的是地址,这是引用类型,那么应该两个都不等吗?

运行结果是:

integer1 == integer2
integer3 != integer4

似乎是个神奇的结论,但是是为什么?

其实是源于一种缓存策略,这种策略会把小数缓存到内存地址里,提高性能和节省内存,实现小数的重用。

当然,这是缓存在Java中仅适用于自动装箱。

接下来我们来看看Java是怎么实现缓存的:

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {<a href="http://www.jobbole.com/members/java12">@code</a> -XX:AutoBoxCacheMax=} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k &amp;lt; cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high &amp;gt;= 127;
        }

        private IntegerCache() {}
    }

实际上,这一范围可以调整JVM启动参数调整,默认是-128-127,通过Integer类第一次被使用来初始化,实现就是一个简单的for循环。

详细阅读:理解Java Integer的缓存策略

看上去还是很简单的,其实Python中也有类似的策略:

尝试一下代码:

>>> x=256
>>> x is 256
True
>>> x=1024
>>> x is 1024
False

is以及id()都是用于比较地址二不是值得,这样比较好明确。

实际上同样的跟Java一样,在解释器运行时也会进行初始化缓存缓存一些数字(当然平时写程序我们应该不会关注到这一点)。

Python的详细解释:

http://stackoverflow.com/questions/4293408/ids-of-immutable-types
之后我还试了试JavaScript,很遗憾并没有这个特性。

植入部分

如果您觉得文章不错,可以通过赞助支持我。

如果您不希望打赏,也可以通过关闭广告屏蔽插件的形式帮助网站运作。

标签: 知识

仅有一条评论

  1. Frank_Kang

    Learned a lot ! Great! In 2012, I go to SMU often since my first gf is there and she study the same lessons . Miss these days.

  2. Frank_Kang

    In fact, you should released and strictly control the memory in coding.

添加新评论