我正在开发一个应用程序,其中一个设计方法涉及到大量使用instanceof操作符。虽然我知道OO设计通常试图避免使用instanceof,但那是另一回事,这个问题纯粹与性能有关。我想知道是否对性能有影响?和==一样快吗?
例如,我有一个有10个子类的基类。在接受基类的单个函数中,我检查类是否是子类的实例并执行一些例程。
我想到的另一种解决方法是使用“type id”整数原语,并使用位掩码来表示子类的类别,然后对子类“type id”与表示类别的常量掩码进行位掩码比较。
instanceof是否被JVM优化得更快?我想坚持使用Java,但应用程序的性能至关重要。如果有人曾经在这条路上走过,可以提供一些建议,那就太棒了。我是不是太挑剔了,或者专注在错误的地方去优化?
将决定性能影响的项目有:
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
InstanceOf是一个糟糕的面向对象设计的警告。
当前的jvm意味着instanceOf本身并不是一个性能问题。如果您发现自己经常使用它,特别是在核心功能方面,那么可能是时候考虑一下设计了。重构为更好的设计所带来的性能(和简单性/可维护性)收益将大大超过实际instanceOf调用所花费的实际处理器周期。
给出一个非常简单的编程示例。
if (SomeObject instanceOf Integer) {
[do something]
}
if (SomeObject instanceOf Double) {
[do something different]
}
是一个糟糕的架构,更好的选择是让SomeObject成为两个子类的父类,其中每个子类重写一个方法(doSomething),这样代码看起来就像这样:
Someobject.doSomething();