integer 緩存及其聯想到的

首先,咱們都知道integer在-128至127(包含),是走緩存的,該緩存設計目的是:節省內存,提升性能。java

猜測,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);
}

返回值以下:git

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

剖析

剖析integer

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

/**
     * 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靜態內部類。其代碼以下:ide

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對象。咱們針對全部的整數類型的類都有相似的緩存機制。ui

ByteCache用於緩存Byte對象
ShortCache用於緩存Short對象
LongCache用於緩存Long對象
CharacterCache用於緩存Character對象

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

相關文章
相關標籤/搜索