標籤: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