开发中不经意的自动拆装箱影响性能问题

在我们开发中会经常用到基本类型的包装类,但是我们很少会去考虑使用过程中带来的问题

下面看一个例子:


问题1:为什么integer j=127;integer j2=127; j==j2,却integer k=128;integer k2=128,k!=k2?

带着这个问题我们看下demo

public class Demo2 {
public static void main(String[] args) {
Integer j=127;
Integer j2=127;
System.out.println(j==j2);
Integer k=128;
Integer k2=128;
System.out.println(k==k2);
}
}

打印结果:

true
false


原因:因为java开发工程师在设计之初考虑到-128-127之间的数值是经常要使用的,如果每次都会new太消耗性能,为此做了一个池,每次都会去这个池子中去找,如果有就从池子里拿,如果没有就在对内存中重新new,这也就解释了为什么127的时候相等,128不相等,因为在127及其以下引用指向的都是池子里同一个地址,注意这个池子也是存在与堆内存中,只不过是静态对象。

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

通过观察远吗我们发现使用的是静态工厂方法维持一个Integer数组,这种思想在很多源码中都有体现,他的好处可以不必每次新建一个对象。

 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 < cache.length; k++)
                cache[k] = new Integer(j++);

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

        private IntegerCache() {}
    }

问题2:拆装箱过程有多耗时?
带着这个疑问我们做个demo。

public class Demo2 {

    public static void main(String[] args) {
        Long sum=0l;
        long start_time=System.currentTimeMillis();
        for(long i=0;i<Integer.MAX_VALUE;i++){
            sum+=i;
        }
        long end_time=System.currentTimeMillis();
        System.out.println(end_time-start_time);
    }
}

**由于在1.5以后自动装箱,自动拆箱让基本数据类型与引用数据类型的之间的差别变得模糊起来,但并没有完全消除,在一些语义上还有微妙的差别,
我测试在Long的情况下耗时:7190
long的情况下耗时:730

因为打错字符,把sum声明成Long而非long,意味着每次都得进行一次装箱
sum+=i;//Long sum=sum+Long.valueof(i);
而这个装箱的过程
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
跟Integer一样,Long.valueof在-128-127中不用新建对象,大于127以后每次都会新建一次Long对象,大约新建了等于2的31次方对象,所以很消耗性能。很耗时

发布了35 篇原创文章 · 获赞 14 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章