instanceof 与 getClass( )
我发现使用 getClass()
和 ==
运算符优于 instanceOf
运算符时性能有所提高。
Object str = new Integer("2000");
long starttime = System.nanoTime();
if (str instanceof String) {
System.out.println("its string");
} else {
if (str instanceof Integer) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime() - starttime));
starttime = System.nanoTime();
if (str.getClass() == String.class) {
System.out.println("its string in equals");
} else {
if (str.getClass() == Integer.class) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime() - starttime));
是否有任何指南,使用 getClass()
或 instanceOf
哪一个?
给定一个场景:我知道要匹配的确切类,即 String
、Integer
(这些是最终类)等。
正在使用 instanceOf
操作员的不良做法?
I see gain in performance when using getClass()
and ==
operator over instanceOf
operator.
Object str = new Integer("2000");
long starttime = System.nanoTime();
if (str instanceof String) {
System.out.println("its string");
} else {
if (str instanceof Integer) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime() - starttime));
starttime = System.nanoTime();
if (str.getClass() == String.class) {
System.out.println("its string in equals");
} else {
if (str.getClass() == Integer.class) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime() - starttime));
Is there any guideline, which one to use getClass()
or instanceOf
?
Given a scenario: I know exact classes to be matched, that is String
, Integer
(these are final classes), etc.
Is using instanceOf
operator bad practice ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
instanceof
和getClass() == ...
的性能1之所以不同,是因为它们在做不同的事情。instanceof
测试左侧 (LHS) 的对象引用是否是右侧 (RHS) 类型的实例或某个子类型 .getClass() == ...
测试类型是否相同。因此,建议忽略性能问题并使用能为您提供所需答案的替代方案。
未必。过度使用
instanceOf
或getClass()
可能“设计味道”。如果您不小心,您最终会得到这样的设计:添加新子类会导致大量代码返工。在大多数情况下,首选方法是使用多态性。然而,在某些情况下,这些并不是“设计气味”。例如,在
equals(Object)
中,您需要测试参数的实际类型,如果不匹配则返回false
。最好使用 getClass() 来完成此操作。1 - 我的答案是假设假设有良好的性能结果表明
getClass()
更快。您提出的基准在许多方面都有缺陷,我们不能相信它产生的结果;请参阅如何用 Java 编写正确的微基准测试?。不管怎样,我提出的观点与表现无关!2 - 应谨慎使用“最佳实践”、“不良实践”、“设计味道”、“反模式”等术语,并以怀疑的态度对待。他们鼓励非黑即白的思维。最好根据具体情况做出判断,而不是纯粹基于教条;例如,有人说是“最佳实践”。我建议每个人都阅读无最佳实践(如果他们还没有这样做的话)。< /sup>
The reason that the performance1 of
instanceof
andgetClass() == ...
is different is that they are doing different things.instanceof
tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.getClass() == ...
tests whether the types are identical.So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.
Not necessarily. Overuse of either
instanceOf
orgetClass()
may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.However, there are cases where these are NOT "design smell". For example, in
equals(Object)
you need to test the actual type of the argument, and returnfalse
if it doesn't match. This is best done usinggetClass()
.1 - My answer was written assuming that there are sound performance results that show that
getClass()
is faster. The benchmark you presented is flawed in a number of respects, and we cannot trust the results it produces; see How do I write a correct micro-benchmark in Java?. Either way, the points I am making are independent of the performance!2 - Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.
您是否想要完全匹配一个类,例如仅匹配
FileInputStream
而不是FileInputStream
的任何子类?如果是这样,请使用getClass()
和==
。我通常会在equals
中执行此操作,以便 X 的实例不被视为等于 X 的子类的实例 - 否则您可能会遇到棘手的对称问题。另一方面,这对于比较属于同一类的两个对象比比较一个特定类的对象更有用。否则,请使用
instanceof
。请注意,使用getClass()
时,您需要确保开始时有一个非空引用,否则您将得到一个NullPointerException
,而instanceof<如果第一个操作数为 null,/code> 将仅返回
false
。就我个人而言,我认为
instanceof
更惯用 - 但在大多数情况下,广泛使用它们中的任何一个都是一种设计味道。Do you want to match a class exactly, e.g. only matching
FileInputStream
instead of any subclass ofFileInputStream
? If so, usegetClass()
and==
. I would typically do this in anequals
, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.Otherwise, use
instanceof
. Note that withgetClass()
you will need to ensure you have a non-null reference to start with, or you'll get aNullPointerException
, whereasinstanceof
will just returnfalse
if the first operand is null.Personally I'd say
instanceof
is more idiomatic - but using either of them extensively is a design smell in most cases.我知道自从问这个问题以来已经有一段时间了,但我昨天学到了一个替代方案
我们都知道你可以这样做:
但是如果你不确切知道它需要什么类型的课程怎么办?
通常你不能这样做:
因为它会给出编译错误。
相反,这里有一个替代方案 - isAssignableFrom()
例如:
I know it has been a while since this was asked, but I learned an alternative yesterday
We all know you can do:
but what if you dont know exactly what type of class it needs to be?
you cannot generically do:
as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()
For example:
getClass() 的限制是对象只能与同一类、同一运行时类型的其他对象相等,如以下代码的输出所示:
输出:
子类扩展了父类。 subClassInstance是ParentClass的实例。
getClass()返回的结果与subClassInstance和parentClassInstance不同。
getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:
Outputs:
SubClass extends ParentClass. subClassInstance is instanceof ParentClass.
Different getClass() return results with subClassInstance and parentClassInstance.