JDK 源碼解析 —— Integer

來源:互聯網
上載者:User

標籤:jdk   源碼解析   效能最佳化   java   integer   


零. 簡介
對於 Integer 這個 Java 程式員幾乎天天使用的類, 使用上卻可以看出普通程式員和優秀程式員區別。


一. 深入代碼
在建立數字 1 的對象時, 大多數人會使用 new Integer(1), 而使用 Integer.valueOf(1) 可以使用系統緩衝,既減少可能的記憶體佔用,也省去了頻繁建立對象的開銷。 

系統預設只緩衝 -128~127 之間的整數。下面我們看一下 Integer.valueOf(int) 方法的代碼: 

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

注意到核心 IntegerCache.cache[i + (-IntegerCache.low)], 觀察 IntegerCache 類的源碼實現:為 -128 ~ 127 數值提供自動裝箱的快取服務。  
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) {            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);        }        high = h;        cache = new Integer[(high - low) + 1];        int j = low;        for(int k = 0; k < cache.length; k++)            cache[k] = new Integer(j++);    }    private IntegerCache() {}}

static 靜態代碼塊可知緩衝的初始化是在第一次使用的時候。 通過 VM 參數-XX:AutoBoxCacheMax=<size> 可以配置緩衝的最大值。 在 VM 初始化期間, 緩衝最大值 high, 可能被儲存在 sun.misc.VM class 的私人系統屬性裡。      


三. 總結
除非是 JDK 1.5 以前的環境, 如果系統不需要新對象, 則推薦使用 Long, Integer, Short, Character, Byte 的 valueOf() 方法提升效能。 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JDK 源碼解析 —— Integer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.