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

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

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

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


当前回答

如果它确实是项目中的性能问题,您应该进行测量/分析。如果是的话,我建议重新设计——如果可能的话。我很确定你不能打败平台的本机实现(用C编写)。在这种情况下,你还应该考虑多重继承。

你应该告诉更多关于这个问题,也许你可以使用一个关联存储,例如Map<Class,对象>如果你只对具体类型感兴趣。

其他回答

InstanceOf是一个糟糕的面向对象设计的警告。

当前的jvm意味着instanceOf本身并不是一个性能问题。如果您发现自己经常使用它,特别是在核心功能方面,那么可能是时候考虑一下设计了。重构为更好的设计所带来的性能(和简单性/可维护性)收益将大大超过实际instanceOf调用所花费的实际处理器周期。

给出一个非常简单的编程示例。

if (SomeObject instanceOf Integer) {
  [do something]
}
if (SomeObject instanceOf Double) {
  [do something different]
}

是一个糟糕的架构,更好的选择是让SomeObject成为两个子类的父类,其中每个子类重写一个方法(doSomething),这样代码看起来就像这样:

Someobject.doSomething();

我只是做了一个简单的测试,看看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循环中)

我也更喜欢枚举方法,但我将使用抽象基类强制子类实现getType()方法。

public abstract class Base
{
  protected enum TYPE
  {
    DERIVED_A, DERIVED_B
  }

  public abstract TYPE getType();

  class DerivedA extends Base
  {
    @Override
    public TYPE getType()
    {
      return TYPE.DERIVED_A;
    }
  }

  class DerivedB extends Base
  {
    @Override
    public TYPE getType()
    {
      return TYPE.DERIVED_B;
    }
  }
}

I'll get back to you on instanceof performance. But a way to avoid problem (or lack thereof) altogether would be to create a parent interface to all the subclasses on which you need to do instanceof. The interface will be a super set of all the methods in sub-classes for which you need to do instanceof check. Where a method does not apply to a specific sub-class, simply provide a dummy implementation of this method. If I didn't misunderstand the issue, this is how I've gotten around the problem in the past.

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.