programing

if(a - b < 0)와 if(a < b)의 차이

yoursource 2022. 9. 3. 17:20
반응형

if(a - b < 0)와 if(a < b)의 차이

바' java java java java java java java java java java java java 를 읽고 있었어요.ArrayListif 스테이트먼트

Java 7에서는 이 메서드는

if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;

6, Java 6의 경우grow존재하지 않았다.단, 이 방법에서는

if (newCapacity < minCapacity)
    newCapacity = minCapacity;

그 변경의 배경은 무엇이었습니까?성능 문제였나요, 아니면 그냥 스타일이었나요?

하는 것이 빠르다고 할 수 하기 위해 은 나에게 인 것처럼 보인다.코드에 는 두 명령어 「 」, 「 」, 「2」, 「2」)가 합니다.ISUB ★★★★★★★★★★★★★★★★★」IF_ICMPGE(1개)IFGE를 참조해 주세요.

a < b ★★★★★★★★★★★★★★★★★」a - b < 0두 가지 다른 의미를 가질 수 있습니다.다음 코드를 고려합니다.

int a = Integer.MAX_VALUE;
int b = Integer.MIN_VALUE;
if (a < b) {
    System.out.println("a < b");
}
if (a - b < 0) {
    System.out.println("a - b < 0");
}

시, 은 행,,, print print print print print print print print print print print print print print print 만 출력됩니다.a - b < 0 일이 a < b 틀렸습니다만,a - b 흐르다-1수입니니다다

그러니까이 지지지음음 .Integer.MAX_VALUEArrayList음음음같 뭇매하다

int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
    newCapacity = hugeCapacity(minCapacity);

oldCapacity 가까이 있다Integer.MAX_VALUEnewCapacity은 (실제)oldCapacity + 0.5 * oldCapacity ( )가 될 수 .Integer.MIN_VALUE(으,으). 뺄게요.minCapacity 언더플로우는 양수로 돌아옵니다.

, 음 this this 、 음 this this this가if을 사용하다가 '다니다'로 if (newCapacity < minCapacity) 될 거예요.true이후)newCapacitynegative에, 「negative(부정)」는newCapacity 수 없이 하게 될 minCapacity에에를 oldCapacity.

이면.newCapacity은 「」, 「」가 .trueMAX_ARRAY_SIZE되어 있습니다.Integer.MAX_VALUE - 8 ★★★★★★★★★★★★★★★★★」Integer.MIN_VALUE - (Integer.MAX_VALUE - 8) > 0true . 。newCapacity따라서 적절하게 처리됩니다.hugeCapacity는 " "를 반환합니다.MAX_ARRAY_SIZE ★★★★★★★★★★★★★★★★★」Integer.MAX_VALUE.

NB는 과 .// overflow-conscious code츠키다

나는 다음과 같은 설명을 발견했다.

9일 화) L2010 3 3 99 ( 03:02 Kevin L.엄하다

빠른 검색을 해보니 자바가 2개의 보완 기반인 것 같습니다.다만, 일반적으로, 이러한 종류의 코드는, 어느 시점에서 누군가가 나타나 Dmytro가 제안한 것을 정확하게 실행할 것으로 충분히 예상되기 때문에, 즉, 누군가가 바뀔 것으로 생각되기 때문에, 나를 불안하게 하고 있습니다.

if (a - b > 0)

로.

if (a > b)

그러면 배 전체가 가라앉을 거야저는 개인적으로 특별한 이유가 없는 한 정수 오버플로를 알고리즘의 필수 기준으로 삼는 것과 같은 불명확한 것은 피하고 싶습니다.일반적으로 오버플로를 완전히 피하고 오버플로의 시나리오를 보다 명확하게 하는 것을 선호합니다.

if (oldCapacity > RESIZE_OVERFLOW_THRESHOLD) {
   // Do something
} else {
  // Do something else
}

좋은 지적입니다.

에서ArrayList이것은 할 수 없습니다(또는 적어도 호환성이 없습니다).ensureCapacity는 퍼블릭 API로, 만족할 수 없는 양의 용량에 대한 요구로서 음수를 이미 받아들입니다.

현재 API는 다음과 같이 사용됩니다.

int newcount = count + len;
ensureCapacity(newcount);

오버플로를 방지하려면 다음과 같은 자연스럽지 않은 것으로 변경해야 합니다.

ensureCapacity(count, len);
int newcount = count + len;

어쨌든 오버플로를 의식한 코드는 유지하되 경고 코멘트를 추가하고 대규모 어레이 작성을 "개요"하여ArrayList의 코드는 다음과 같습니다.

/**
 * Increases the capacity of this <tt>ArrayList</tt> instance, if
 * necessary, to ensure that it can hold at least the number of elements
 * specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
public void ensureCapacity(int minCapacity) {
    modCount++;

    // Overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

/**
 * The maximum size of array to allocate.
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/**
 * Increases the capacity to ensure that it can hold at least the
 * number of elements specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    // Overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);

    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

private int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

웹이 재생성되었습니다.

마틴

Java 6에서는 API를 다음과 같이 사용합니다.

int newcount = count + len;
ensureCapacity(newcount);

그리고.newCount오버플로우(음수가 됩니다),if (minCapacity > oldCapacity)false가 반환되어 잘못 추측할 수 있습니다.ArrayList에 의해 증가했다.len.

코드 보기:

int newCapacity = oldCapacity + (oldCapacity >> 1);

한다면oldCapacity꽤 크고, 이것은 넘칠 것입니다.newCapacity음수가 됩니다.와 같은 비교newCapacity < oldCapacity잘못 평가하다true및 그ArrayList성장하지 못할 것이다.

그 대신에, 코드는 기재되어 있습니다(newCapacity - minCapacity < 0returns false)는 다음 음수 값을 허용합니다.newCapacity다음 행에서 추가 평가되어 재계산된다.newCapacity""를 hugeCapacity )newCapacity = hugeCapacity(minCapacity);를 할 수 있도록 합니다.ArrayListMAX_ARRAY_SIZE.

'우리'가 말하는 예요.// overflow-conscious code코멘트는 다소 비스듬히 전달하려고 합니다.

이 는 '비교'가 '비교', '비교', '비교', '비교'를 하는 것을 합니다.ArrayList 정의된 것보다 MAX_ARRAY_SIZE필요에 따라 그 한계까지 확장할 수 있습니다.

두 는 '라는 표현이 아니면 똑같이 동작합니다.a - b오버플로우(이 경우 반대). ifa 음수, 큰 음수입니다.b 큰 플러스, 큰 양의 양수입니다.(a < b) 사실이지만a - b 긍정적이 에, 「적극적」입니다.(a - b < 0)짓입니니다다

코드를 잘 x86을 고려해 .(a < b)에 의해 실장됩니다.jgeSF = OF 때 、 의 sf sf 、 sf sf sf sf sf sf sf sf sf sf sf sf sf sf sf 。 반,는(a - b < 0) jnsSF = 0 일 sf sf sf sf sf sf sf sf 。따라서 OF = 1일 때 이 두 값은 서로 다른 정밀도로 동작합니다.

언급URL : https://stackoverflow.com/questions/33147339/difference-between-if-a-b-0-and-if-a-b

반응형