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

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

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

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


当前回答

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.

其他回答

一般来说,在这种情况下(instanceof检查这个基类的子类)不支持使用“instanceof”操作符的原因是,您应该做的是将操作移动到一个方法中,并为适当的子类重写它。例如,如果你有:

if (o instanceof Class1)
   doThis();
else if (o instanceof Class2)
   doThat();
//...

你可以用

o.doEverything();

然后在Class1中调用“doEverything()”的实现,在Class2中调用“doThat()”,以此类推。

关于Peter Lawrey的注释,final类不需要instanceof,只需使用一个引用相等,请小心!即使最终的类不能扩展,也不能保证它们由相同的类加载器加载。只有在绝对肯定这段代码只有一个类加载器时,才使用x.getClass() == SomeFinal.class或类似的类加载器。

将决定性能影响的项目有:

The number of possible classes for which the instanceof operator could return true The distribution of your data - are most of the instanceof operations resolved in the first or second attempt? You'll want to put your most likely to return true operations first. The deployment environment. Running on a Sun Solaris VM is significantly different than Sun's Windows JVM. Solaris will run in 'server' mode by default, while Windows will run in client mode. The JIT optimizations on Solaris, will make all method access able the same.

我为四种不同的分派方法创建了一个微基准测试。Solaris的结果如下所示,数值越小越快:

InstanceOf 3156
class== 2925 
OO 3083 
Id 3067 

很难说一个特定的JVM是如何实现实例的,但在大多数情况下,对象与结构相当,类也是如此,每个对象结构都有一个指向它是实例的类结构的指针。实际上是instanceof for

if (o instanceof java.lang.String)

可能和下面的C代码一样快

if (objectStruct->iAmInstanceOf == &java_lang_String_class)

假设JIT编译器已经就位,并且工作出色。

考虑到这只是访问一个指针,在指针指向的某个偏移量处获得一个指针,并将其与另一个指针进行比较(这基本上与测试32位数字是否相等相同),我认为操作实际上可以非常快。

但是,这并不一定是必须的,它在很大程度上取决于JVM。但是,如果这将成为代码中的瓶颈操作,我认为JVM实现相当糟糕。即使没有JIT编译器,只解释代码,也应该能够在几乎没有时间的情况下创建一个实例测试。

现代JVM/JIT编译器已经消除了大多数传统的“慢”操作对性能的影响,包括instanceof、异常处理、反射等。

正如Donald Knuth所写的,“我们应该忘记小的效率,大约97%的时候:过早的优化是万恶之源。”instanceof的性能可能不是问题,所以在确定问题所在之前,不要浪费时间想出奇异的解决方案。