首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在现代JVM实现中,instanceof是如何实现的?

在现代JVM实现中,instanceof是如何实现的?
EN

Stack Overflow用户
提问于 2012-09-12 19:07:57
回答 1查看 1.9K关注 0票数 2

由于在其他线程中完成了基准测试(参见https://stackoverflow.com/a/397617/1408611)表明,在Java6中的instanceof实际上是相当快的。这是如何实现的?

我知道对于单继承,最快的想法是使用一些嵌套的区间编码,其中每个类维护一个低的,高的区间,而instanceof仅仅是一个区间包含测试,即2个整数比较。但它是如何为接口制作的(因为区间包含只适用于单一继承)?类加载是如何处理的呢?加载新的子类意味着需要调整很多时间间隔。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-12 19:15:31

AFAIK每个类都知道它扩展的所有类和它实现的接口。这些可以存储在哈希集中,从而提供O(1)的查找时间。

当代码经常采用相同的分支时,成本几乎可以被消除,因为CPU可以在确定是否应该采用该分支之前执行该分支中的代码,从而使成本几乎为零。

由于微基准测试是在4年前执行的,我预计最新的CPU和JVM会快得多。

代码语言:javascript
复制
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;
}

最后打印出来

代码语言:javascript
复制
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

如果我把“替身”换成

代码语言:javascript
复制
    for(int i=0;i<doubles.length;i+=2)
        doubles[i] = "";

我得到了

代码语言:javascript
复制
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

注意:如果我改变了

代码语言:javascript
复制
if (d instanceof Double)

代码语言:javascript
复制
if (d != null && d.getClass() == Double.class)

表现也是一样的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12386789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档