Integer 如何實現節約內存和提升性能的

在Java5中,爲Integer的操作引入了一個新的特性,用來節省內存和提高性能。整型對象在內部實現中通過使用相同的對象引用實現了緩存和重用。
上面的規則默認適用於整數區間 -128 到 +127(這個整數區間可以通過啓動應用的虛擬機參數修改:-XX:AutoBoxCacheMax)。

這種Integer緩存策略僅在自動裝箱(autoboxing)的時候有用,使用構造器創建的Integer對象不能被緩存。Java 編譯器把原始類型自動轉換爲封裝類的過程稱爲自動裝箱(autoboxing),這相當於調用 valueOf 方法。

在這裏插入圖片描述

如果面試官問Integer與int的區別:估計大多數人只會說道兩點,Ingeter是int的包裝類,int的初值爲0,Ingeter的初值 爲null。

但是如果面試官再問一下Integer i = 1;int ii = 1; i==ii爲true還是爲false?估計就有一部分人答不出來了,如果再問一下其他的,估計更多的人會頭腦一片混亂。

首先看代碼:

public static void main(String[] args) {
        int a = 127;
        int a1 = 128;
        int a2 = 128;
        int a3 = 127;

        Integer b = 127;
        Integer b1 = 128;
        Integer b2 = 127;
        Integer b3 = 128;
        Integer c = new Integer(127);
        Integer c1 = new Integer(128);
        Integer c2 = new Integer(128);
        Integer c4 = new Integer(127);

        System.out.println(a1==a2);//true
        System.out.println(a==b);//true
        System.out.println(a==a3);//true
        System.out.println(a2==b1);//true
        System.out.println(a==c);//true
        System.out.println(b==c);//false
        System.out.println(c1==c2);//false
        System.out.println(c1==a1);//true
        System.out.println(c==c4);//false
        System.out.println(b==b2);//true
        System.out.println(b1==b3);//false

        int m = 60;
        String n = "60";
        System.out.println(m+n);//6060
        System.out.println(n+m);//6060



    }

關鍵就是看valueOf()函數了。只要看看valueOf()函數的源碼就會明白了。JDK源碼的 valueOf函數式這樣的:
在這裏插入圖片描述
看一下源碼大家都會明白,對於-128到127之間的數,會進行緩存,Integer a = 127時,會將127進行緩存,下次再寫Integer b = 127時,就會直接從緩存中取,就不會new了。所以結果爲true。

對於以上的情況總結如下:

1.無論如何,Integer與new Integer不會相等。不會經歷拆箱過程,i3的引用指向堆,而i4指向專門存放他的內存(常量池),他們的內存地址不一樣,所以爲false 2.兩個都是非new出來的Integer,如果數在-128到127之間,則是true,否則爲false。java在編譯Integer i2 = 128的時候,被翻譯成-> Integer i2 = Integer.valueOf(128);而valueOf()函數會對-128到127之間的數進行緩存。

3.兩個都是new出來的,都爲false。

4.int和Integer(無論new否)比,都爲true,因爲會把Integer自動拆箱爲int再去比。

AUTOBOXCACHEMAX參數:
在這裏插入圖片描述
-XX:AutoBoxCacheMax這個參數是設置Integer緩存上限的參數,在VM初始化期間java.lang.Integer.IntegerCache.high屬性可以被設置和保存在私有的系統屬性sun.misc.VM class中。理論上講,當系統需要頻繁使用Integer時,或者說堆內存中存在大量的Integer對象時,可以考慮提高Integer緩存上限,避免JVM重複創造對象,提高內存的使用率,減少GC的頻率,從而提高系統的性能。

理論歸理論,這個參數能否提高系統系統關鍵還是要看堆中Integer對象到底有多少、以及Integer的創建的方式。如果堆中的Integer對象很少,重新設置這個參數並不會提高系統的性能。即使堆中存在大量的Integer對象,也要看Integer對象時如何產生的

1.大部分Integer對象通過Integer.valueOf()產生。說明代碼裏存在大量的拆箱與裝箱操作。這時候設置這個參數會系統性能有所提高。

2.大部分Integer對象通過反射,new產生。這時候Integer對象的產生大部分不會走valueOf()方法,所以設置這個參數也是無濟於事。

JDK中其他類似的緩存

Integer的緩存上限可以通過Java虛擬機參數修改,Byte、Short、Long、Character的緩存則沒法修改。

Byte
在這裏插入圖片描述
Short
在這裏插入圖片描述
Long
在這裏插入圖片描述
Character
在這裏插入圖片描述
示例:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章