programing

새로운 정수 대 valueOf

nasanasas 2020. 11. 5. 08:09
반응형

새로운 정수 대 valueOf


내가 사용하던 수중 음파 탐지기를 내 코드 청소기를 만들기 위해, 그리고 내가 사용하고 있다고 지적 new Integer(1)대신 Integer.valueOf(1). valueOf새 객체를 인스턴스화하지 않는 것처럼 보이므로 메모리 친화적입니다. valueOf새 개체를 어떻게 인스턴스화 할 수 없습니까? 어떻게 작동합니까? 모든 정수에 대해 사실입니까?


Integer.valueOf는 -128에서 +127 사이의 값에 대한 캐시를 구현합니다. boxing에 대한 요구 사항을 설명하는 Java 언어 사양 섹션 5.1.7의 마지막 단락을 참조하십시오 (일반적으로 .valueOf 메서드로 구현 됨).

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7


로부터 의 JavaDoc :

public static Integer valueOf (int i) 지정된 int 값을 나타내는 Integer 인스턴스를 반환합니다. 새 Integer 인스턴스가 필요하지 않은 경우이 메서드는 자주 요청되는 값을 캐싱하여 훨씬 더 나은 공간 및 시간 성능을 얻을 수 있으므로 일반적으로 Integer (int) 생성자보다이 메서드를 우선적으로 사용해야합니다.

ValueOf 일반적으로 오토 박싱에 사용되므로 (오토 박싱에 사용될 때) 오토 박싱 사양을 따르기 위해 적어도 -128에서 127 사이의 값을 캐시합니다.

다음은 valueOfSun JVM 1.5에 대한 구현입니다.? 캐시가 초기화되는 방법을 보려면 전체 클래스를 살펴보십시오.

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}

valueOf()대신 사용하도록 강요 하고 new Integer()있으므로 메서드 valueOf()대신 사용 하고 나중에 동일한 숫자를 다시 얻으려는 경우 값을 캐시합니다. 이 경우 메서드는 새로운 Integer를 instatiate하지 않지만 캐시 된 것을 제공합니다. 새로운 Integer의 '생성'을 훨씬 더 빠르고 메모리 친화적 인 프로세스로 만듭니다.

이 방법을 사용하면 경험이없는 자바 프로그래머라면 많은 문제를 일으킬 수 있습니다 Integer.valueOf(342)==Integer.valueOf(342). 왜냐하면 두 개의 Integer에 대해 동일한 포인터를 가질 수도 있고 아닐 수도 있고 아마도 어떤 방식으로 연습 할 수도 있기 때문입니다. 당신은 C #에서 배웠기 때문에 때때로 버그를 보여줄 것입니다. 그리고 당신은 그 버그가 어디서 어떻게 왔는지 모를 것입니다.


java.lang.Integer 소스 코드에서. 정수 캐시는 구성 가능합니다. Sun 이외의 Integer 캐시 크기를 구성하려면 java.lang.Integer.IntegerCache.high소스 코드에 따라 System 속성을 사용해야합니다 .

/**
 * 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. During VM initialization the
 * getAndRemoveCacheProperties method may be used to get and remove any system
 * properites that configure the cache size. At this time, the size of the
 * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
 */

// value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
private static String integerCacheHighPropValue;

static void getAndRemoveCacheProperties() {
    if (!sun.misc.VM.isBooted()) {
        Properties props = System.getProperties();
        integerCacheHighPropValue =
            (String)props.remove("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null)
            System.setProperties(props);  // remove from system props
    }
}

private static class IntegerCache {
    static final int high;
    static final Integer cache[];

    static {
        final int low = -128;

        // high value may be configured by property
        int h = 127;
        if (integerCacheHighPropValue != null) {
            // Use Long.decode here to avoid invoking methods that
            // require Integer's autoboxing cache to be initialized
            int i = Long.decode(integerCacheHighPropValue).intValue();
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - -low);
        }
        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() {}
}

java.lang.Short, java.lang.Byte 및 java.lang.Long에서 127에서 -128의 캐시를 만듭니다.

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);
    }
}

private static class ShortCache {
    private ShortCache() {
    }

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

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

private static class ByteCache {
    private ByteCache() {
    }

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

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

참고 URL : https://stackoverflow.com/questions/2974561/new-integer-vs-valueof

반응형