HihoBookStudy / EffectiveJava

이펙티브 자바 북스터디입니다.
1 stars 0 forks source link

[Item 14] compareTo() 구현 #23

Closed ForteEscape closed 2 months ago

ForteEscape commented 3 months ago

Q. 책(p.91)에서 다음과 같이 언급하고 있습니다.

compareTo 연산에서 관계 연산자 <, >를 사용하는 이전 방식은 거추장스럽고 오류를 유발하니 사용을 추천하지 않는다.

Limgayoung commented 2 months ago

<, >를 이용해 compareTo를 구현한 클래스와 compare() 메서드를 사용해 compareTo를 구현한 동일한 인자를 가진 클래스 각각에 대해 PriorityQueue로 테스트 해봤습니다.

compare() 메서드를 사용한 경우가 아주 조금 더 느리지만 거의 비슷한 성능을 보입니다. 책에서 말하는 오류는 Human Error를 말하는 것 같고, 성능이 거의 비슷하기 때문에 compare() 메서드를 권장하는 것 같습니다.

테스트 코드입니다.

package effectiveJavamain.java.javastudy.effectiveJava.Chapter3.item14;

import java.awt.Point;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import static java.util.Comparator.*;

public class Test{

    public static class TestClass implements Comparable<TestClass>{
        int x;

        public TestClass(int x) {
            super();
            this.x = x;
        }

        @Override
        public int compareTo(TestClass o) {
            if(this.x == o.x) return 0;
            else if(this.x < o.x) return -1;
            else return 1;
        }
    }

    public static class TestClass2 implements Comparable<TestClass2>{
        int x;

        public TestClass2(int x) {
            super();
            this.x = x;
        }

        @Override
        public int compareTo(TestClass2 o) {
            return Integer.compare(this.x, o.x);
        }
    }

    public static void main(String[] args) {

        PriorityQueue<TestClass> pqOper = new PriorityQueue<>();
        PriorityQueue<TestClass2> pqCompareTo = new PriorityQueue<>();

        int compareNum = 1;                     

        long seed = System.currentTimeMillis();
        Random rand = new Random(seed);

        long before = System.currentTimeMillis();
        for(int i=0;i<100000000;i++) {          
            pqOper.add(new TestClass(rand.nextInt()));
        }
        System.out.println("Time Required for Oper: "+ (System.currentTimeMillis()-before));

        rand = new Random(seed);
        before = System.currentTimeMillis();
        for(int i=0;i<100000000;i++) {          
            pqCompareTo.add(new TestClass2(rand.nextInt()));
        }
        System.out.println("Time Required for compareTo: "+ (System.currentTimeMillis()-before));
    }

}

결과입니다.

Time Required for Oper: 4433
Time Required for compareTo: 4456