AFAIK 每个类都知道它扩展的所有类和它实现的接口。这些可以存储在哈希集中,从而提供 O(1) 查找时间。
当代码经常采用相同的分支时,成本几乎可以消除,因为 CPU 可以在确定是否应该采用该分支之前执行分支中的代码,从而使成本几乎为零。
由于微基准测试是在 4 年前进行的,我预计最新的 CPU 和 JVM 会更快。
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.3 ns
instanceof Serializable took an average of 1.3 ns
如果我改变“双打”
for(int i=0;i<doubles.length;i+=2)
doubles[i] = "";
I get
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
注意:如果我改变
if (d instanceof Double)
to
if (d != null && d.getClass() == Double.class)
表现是一样的。