1. 程式人生 > >integer 快取及其聯想到的

integer 快取及其聯想到的

首先,我們都知道integer在-128至127(包含),是走快取的,該快取設計目的是:節省記憶體,提高效能。

猜想,Long是否也存在類似快取設計?

public static void main(String[] args) {
    Integer integer1 = 3;
    Integer integer2 = 3;
    System.out.printf("integer1 == integer2:[%s]\n", integer1 == integer2);

    Integer integer3 = 300;
    Integer integer4 = 300;
    System.out.printf("integer3 == integer4結果:[%s]\n", integer3 == integer4);

    System.out.println("--------換行----------");
    Long long1 = 3L;
    Long long2 = 3L;
    System.out.printf("long1 == long2:結果:[%s]\n", long1 == long2);

    Long long3 = 300L;
    Long long4 = 300L;
    System.out.printf("long3 == long4:結果:[%s]\n", long3 == long4);
}

返回值如下:

integer1 == integer2:[true]
integer3 == integer4結果:[false]
--------換行----------
long1 == long2:結果:[true]
long3 == long4:結果:[false]

剖析

剖析integer

java.lang.integer類中有個private static class IntegerCache靜態內部類。其javadoc如下:

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

其最大值(high)可以通過-XX:AutoBoxCacheMax=<size>屬性來指定,但程式碼中有判斷,確保其不可小於127

剖析Long

java.lang.Long類中有個private static class LongCache靜態內部類。其程式碼如下:

private static class LongCache {
    private LongCache(){}

    static final Long cache[] = new Long[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Long(i - 128);
    }
}

參考連結

下面這段文字,來自:https://github.com/hollischuang/toBeTopJavaer/blob/master/basics/java-basic/integer-cache.md

這種快取行為不僅適用於Integer物件。我們針對所有的整數型別的類都有類似的快取機制。

ByteCache用於快取Byte物件
ShortCache用於快取Short物件
LongCache用於快取Long物件
CharacterCache用於快取Character物件

Byte, Short, Long有固定範圍: -128 到 127。對於Character, 範圍是 0 到 127。除了Integer以外,這個範圍都不能