Java的Integer緩存池用法
Java的Integer緩沖池?
Integer 緩存池主要為了提升性能和節(jié)省內(nèi)存。根據(jù)實踐發(fā)現(xiàn)大部分的數(shù)據(jù)操作都集中在值比較小的范圍,因此緩存這些對象可以減少內(nèi)存分配和垃圾回收的負(fù)擔(dān),提升性能。
在-128到 127范圍內(nèi)的 Integer 對象會被緩存和復(fù)用。
原理
int 在自動裝箱的時候會調(diào)用Integer.valueOf
,進而用到了 IntegerCache。
@HotSpotIntrinsicCandidate public static Integer value0f(int i){ if(i>= IntegerCache.low && i<= IntegerCache.high) //如果傳入的int值在緩存范圍內(nèi),則直接從緩存中返回Integer對象 return IntegerCache.cache[i+(-IntegerCache.low)]; return new Integer(i); //否則,創(chuàng)建新的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 = VM.getSavedProperty( key:"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 i = low; for(int k=0;k< cache.length; k++) //遍歷創(chuàng)建-128-127的所有對象 cache[k]= new Integer(i++); assert IntegerCache.high >= 127; } private IntegerCache(){} }
所以這里還有個面試題:就是為啥 Integer 127 之內(nèi)的相等,而超過 127 的就不等了?
因為小于等于127的 Integer
對象是從同一個緩存池中獲取的,它們指向的是相同的對象實例,所以它們的引用相等
不僅 Integer 有,Long 同樣有一個緩存池,不過范圍是寫死的 -128 到 127,不能通過JVM參數(shù)進行調(diào)整
@HotSpotIntrinsicCandidate public static Long value0f(long l){ final int offset = 128; if(l>= -128 &&l<= 127){ // will cache return LongCache.cache[(int)l + offsetl]; } return new Long(l); }
總結(jié)
- Byte,Short,Integer,Long這4種包裝類默認(rèn)創(chuàng)建了數(shù)值[-128,127]的相應(yīng)類型的緩存數(shù)據(jù)
- Character 創(chuàng)建了數(shù)值在 [0,127]范圍的緩存數(shù)據(jù)
- Boolean 直接返回 True or False
- Float 和 Double 沒有緩存數(shù)據(jù),畢竟是小數(shù),能存的數(shù)太多了
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot根據(jù)目錄結(jié)構(gòu)自動生成路由前綴的實現(xiàn)代碼
本文介紹如何根據(jù)目錄結(jié)構(gòu)給RequestMapping添加路由前綴,具體實現(xiàn)方法,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08

java實現(xiàn)獲取網(wǎng)站的keywords,description

Struts2學(xué)習(xí)筆記(9)-Result配置全局結(jié)果集

BootStrap Jstree 樹形菜單的增刪改查的實現(xiàn)源碼

Java報錯:FileNotFoundException的解決方案