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

本文探讨了Java中基本类型包装类在使用时可能存在的性能问题,特别是Integer对象在-128到127之间的缓存机制导致的不同结果。通过示例代码展示了127及以下数值比较时为何返回true,而128及以上数值比较返回false。此外,还分析了拆装箱过程的时间消耗,并以Long为例,说明了在特定情况下装箱操作可能导致大量对象创建,从而影响性能。

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

下面看一个例子:


问题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次方对象,所以很消耗性能。很耗时

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值