CodeSky 代码之空

随手记录自己的学习过程

Integer缓存策略

2016-08-07 14:39分类: Java评论: 2

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

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

1public class JavaIntegerCache {
2    public static void main(String... strings) {
3
4        Integer integer1 = 3;
5        Integer integer2 = 3;
6
7        if (integer1 == integer2)
8            System.out.println("integer1 == integer2");
9        else
10            System.out.println("integer1 != integer2");
11
12        Integer integer3 = 300;
13        Integer integer4 = 300;
14
15        if (integer3 == integer4)
16            System.out.println("integer3 == integer4");
17        else
18            System.out.println("integer3 != integer4");
19
20    }
21}
22

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

运行结果是:

integer1 == integer2
integer3 != integer4

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

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

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

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

1/**
2     * Cache to support the object identity semantics of autoboxing for values between
3     * -128 and 127 (inclusive) as required by JLS.
4     *
5     * The cache is initialized on first usage.  The size of the cache
6     * may be controlled by the {<a href="http://www.jobbole.com/members/java12">@code</a> -XX:AutoBoxCacheMax=} option.
7     * During VM initialization, java.lang.Integer.IntegerCache.high property
8     * may be set and saved in the private system properties in the
9     * sun.misc.VM class.
10     */
11
12    private static class IntegerCache {
13        static final int low = -128;
14        static final int high;
15        static final Integer cache[];
16
17        static {
18            // high value may be configured by property
19            int h = 127;
20            String integerCacheHighPropValue =
21                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
22            if (integerCacheHighPropValue != null) {
23                try {
24                    int i = parseInt(integerCacheHighPropValue);
25                    i = Math.max(i, 127);
26                    // Maximum array size is Integer.MAX_VALUE
27                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
28                } catch( NumberFormatException nfe) {
29                    // If the property cannot be parsed into an int, ignore it.
30                }
31            }
32            high = h;
33
34            cache = new Integer[(high - low) + 1];
35            int j = low;
36            for(int k = 0; k &amp;lt; cache.length; k++)
37                cache[k] = new Integer(j++);
38
39            // range [-128, 127] must be interned (JLS7 5.1.7)
40            assert IntegerCache.high &amp;gt;= 127;
41        }
42
43        private IntegerCache() {}
44    }
45

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

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

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

尝试一下代码:

1>>> x=256
2>>> x is 256
3True
4>>> x=1024
5>>> x is 1024
6False
7

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

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

Python的详细解释:

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

评论 (2)

Frank_Kang2017年6月16日 16:22

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

Frank_Kang2017年6月15日 13:45

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.