AFAIK 각 클래스는 자신이 확장하고 인터페이스를 구현하는 모든 클래스를 알고 있습니다. 이것들은 O (1) 검색 시간을 제공하는 해시 세트에 저장 될 수 있습니다.
코드가 자주 동일한 분기를 사용하는 경우 CPU가 분기에서 코드를 실행하기 전에 비용을 거의 없앨 수 있으므로 비용을 없애는 분기를 사용해야하는지 여부가 결정됩니다.
마이크로 벤치 마크가 4 년 전에 수행 되었기 때문에 최신 CPU와 JVM이 훨씬 더 빠를 것으로 기대합니다. 내가
0,123,516을 변경하는 경우 : 나는
for(int i=0;i<doubles.length;i+=2)
doubles[i] = "";
으로 "더블"을 변경하는 경우
public static void main(String... args) {
Object[] doubles = new Object[100000];
Arrays.fill(doubles, 0.0);
doubles[100] = null;
doubles[1000] = null;
for (int i = 0; i < 6; i++) {
testSameClass(doubles);
testSuperClass(doubles);
testInterface(doubles);
}
}
private static int testSameClass(Object[] doubles) {
long start = System.nanoTime();
int count = 0;
for (Object d : doubles) {
if (d instanceof Double)
count++;
}
long time = System.nanoTime() - start;
System.out.printf("instanceof Double took an average of %.1f ns%n", 1.0 * time/doubles.length);
return count;
}
private static int testSuperClass(Object[] doubles) {
long start = System.nanoTime();
int count = 0;
for (Object d : doubles) {
if (d instanceof Number)
count++;
}
long time = System.nanoTime() - start;
System.out.printf("instanceof Number took an average of %.1f ns%n", 1.0 * time/doubles.length);
return count;
}
private static int testInterface(Object[] doubles) {
long start = System.nanoTime();
int count = 0;
for (Object d : doubles) {
if (d instanceof Serializable)
count++;
}
long time = System.nanoTime() - start;
System.out.printf("instanceof Serializable took an average of %.1f ns%n", 1.0 * time/doubles.length);
return count;
}
마침내 내가
instanceof Double took an average of 1.3 ns
instanceof Number took an average of 1.6 ns
instanceof Serializable took an average of 2.2 ns
주
을 얻을
instanceof Double took an average of 1.3 ns
instanceof Number took an average of 1.3 ns
instanceof Serializable took an average of 1.3 ns
를 인쇄
if (d instanceof Double)
if (d != null && d.getClass() == Double.class)
에 성능과 동일하다.
또한이 해시 테이블 접근 방식에 대해서도 생각하고있었습니다. 그러나 instanceof는 해시 테이블 조회보다 더 빠른 경우도 있습니다. 매개 변수가없는 단일 함수 호출보다 훨씬 빠릅니다. – gexicide
생성 된 코드는 인라인 될 수 있습니다. 위의'Double'의 경우, 클래스가'final'이므로 테스트는'd! = null && d.getClass() == Double.class'와 동일합니다. –