java instanceof 原理_java-在现代JVM实现中如何实现instanceof?

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[i] = "";

我懂了

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)

if (d != null && d.getClass() == Double.class)

表现是一样的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值