Closed ForteEscape closed 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
Q. 책(p.91)에서 다음과 같이 언급하고 있습니다.
<
,>
에 대해서는 boxing이 수반되지 않으므로 성능 상 이점을 가져갈 수 있을 것으로 보입니다. 이런 성능상 이점을 뛰어넘을 정도로compare()
메서드를 사용해야 하는지에 대한 생각과 그 이유가 궁금합니다.