단일 비교를 하는 경우 IN()절로 작성한 SQL을 재사용해도 좋을지 궁금해서 찾아봤는데 괜찮아보이는 글이 보였다. 대체로 차이가 없다는 의견이지만 공식 문서는 없는 것 같아서 간단하게 테스트를 해봤다.

 

 

Performance differences between equal (=) and IN with one literal value

How does SQL engines differ when we use equal sign and IN operator have same value? Does execution time changes? 1st one using equality check operator WHERE column_value = 'All' 2nd one using IN

stackoverflow.com

 

spot_id IN(1), spot_id = 1 모두 동등 비교를 하고 실행 계획 type도 ref로 나왔다. ref는 동등 조건으로 검색할 때의 접근 방법을 나타낸다.

 

IN 절에 여러 id가 들어가는 경우에는 id = 1 or id = 2.. 형태로 된다.

 

Stack 자료구조의 특정 객체를 파라미터로 받아서 해당 요소가 있으면 위치를 반환해주는 search() 메서드를 구현해보던 중 equals()로 비교를 할 때, 전달 받은 파라미터가 null인 경우를 따로 체크하는 부분이 있었다.

 

public synchronized int lastIndexOf(Object o, int index) {
    if (index >= elementCount)
        throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

    // Obect o 객체가 null 인 경우
    if (o == null) {
        for (int i = index; i >= 0; i--)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = index; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

 

equals()를 사용할 때는 주의해야 될 부분이 있는데 값을 비교할 때 앞에 null인 객체가 들어올 경우 NullPointerException 예외가 발생하는 것이다. 

public int lastIndexOf(Object value) {
    int index = array.length - 1;
    for (int i = index; i >= 0; i--) {
        // value가 Null인 경우
        if (value.equals(array[i])) {
            return i;
        }
    }
    return -1;
}

 

객체 참조를 하기 때문에 당연한 부분이지만 전에도 이런 실수를 많이 했던 것 같다. 그래서 객체와 문자열의 값을 비교하는 경우에는 문자열을 왼쪽에 입력하고, 객체끼리 비교하는 경우에는 null 값을 고려해서 코드를 짜도록 해야겠다.

+ Recent posts