開發中不經意的自動拆裝箱影響性能問題

在我們開發中會經常用到基本類型的包裝類,但是我們很少會去考慮使用過程中帶來的問題

下面看一個例子:


問題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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章