我正在开发一个应用程序,其中一个设计方法涉及到大量使用instanceof操作符。虽然我知道OO设计通常试图避免使用instanceof,但那是另一回事,这个问题纯粹与性能有关。我想知道是否对性能有影响?和==一样快吗?

例如,我有一个有10个子类的基类。在接受基类的单个函数中,我检查类是否是子类的实例并执行一些例程。

我想到的另一种解决方法是使用“type id”整数原语,并使用位掩码来表示子类的类别,然后对子类“type id”与表示类别的常量掩码进行位掩码比较。

instanceof是否被JVM优化得更快?我想坚持使用Java,但应用程序的性能至关重要。如果有人曾经在这条路上走过,可以提供一些建议,那就太棒了。我是不是太挑剔了,或者专注在错误的地方去优化?


当前回答

'instanceof'实际上是一个运算符,就像+或-,我相信它有自己的JVM字节码指令。应该够快了。

我不应该说,如果你有一个开关,你正在测试一个对象是否是某个子类的实例,那么你的设计可能需要重做。考虑将特定于子类的行为下推到子类本身。

其他回答

在现代Java版本中,instanceof操作符作为一个简单的方法调用更快。这意味着:

if(a instanceof AnyObject){
}

为:

if(a.getType() == XYZ){
}

另一件事是如果你需要级联许多instanceof。然后,只调用一次getType()的切换会更快。

回答你的最后一个问题:除非分析人员告诉你,你在某个实例上花费了大量的时间:是的,你在吹毛求疵。

在考虑优化从来不需要优化的东西之前:以最易读的方式编写算法并运行它。运行它,直到jit编译器有机会优化它自己。如果这段代码有问题,可以使用分析器来告诉您,在哪里可以获得最大收益并进行优化。

在高度优化编译器的时代,您对瓶颈的猜测很可能是完全错误的。

在这个答案的真正精神(我完全相信):一旦jit编译器有机会优化它,我绝对不知道instanceof和==是如何关联的。

我忘了:永远不要测量第一次运行。

我只是做了一个简单的测试,看看instanceOf的性能如何与对一个只有一个字母的字符串对象的简单s.equals()调用进行比较。

在10.000.000循环中,instanceOf给了我63-96ms,而字符串equals给了我106-230ms

我使用java jvm 6。

所以在我的简单测试中,做一个instanceOf而不是一个字符串比较更快。

使用Integer的.equals()而不是string的给了我相同的结果,只有当我使用== I比instanceOf快20ms(在10.000.000循环中)

You're focusing on the wrong thing. The difference between instanceof and any other method for checking the same thing would probably not even be measurable. If performance is critical then Java is probably the wrong language. The major reason being that you can't control when the VM decides it wants to go collect garbage, which can take the CPU to 100% for several seconds in a large program (MagicDraw 10 was great for that). Unless you are in control of every computer this program will run on you can't guarantee which version of JVM it will be on, and many of the older ones had major speed issues. If it's a small app you may be ok with Java, but if you are constantly reading and discarding data then you will notice when the GC kicks in.

我基于jmh-java-benchmark- prototype:2.21编写了一个性能测试。JDK为openjdk, version为1.8.0_212。测试机器是mac pro。 测试结果为:

Benchmark                Mode  Cnt    Score   Error   Units
MyBenchmark.getClasses  thrpt   30  510.818 ± 4.190  ops/us
MyBenchmark.instanceOf  thrpt   30  503.826 ± 5.546  ops/us

结果表明:getClass优于instanceOf,这与其他测试结果相反。然而,我不知道为什么。

测试代码如下:

public class MyBenchmark {

public static final Object a = new LinkedHashMap<String, String>();

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean instanceOf() {
    return a instanceof Map;
}

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean getClasses() {
    return a.getClass() == HashMap.class;
}

public static void main(String[] args) throws RunnerException {
    Options opt =
        new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).warmupIterations(20).measurementIterations(30).forks(1).build();
    new Runner(opt).run();
}
}