简体   繁体   English

更快的是:instanceof或isInstance?

[英]What's faster: instanceof or isInstance?

Design questions aside, what performs faster on modern JVMs? 除了设计问题,现代JVM的执行速度更快?

foo instanceof Bar

or 要么

Bar.class.isInstance(foo)

Why? 为什么?

Class.isInstance is JVM intrinsic. Class.isInstance是JVM固有的。 It is compiled to exactly the same sequence as instanceof does (the proof from HotSpot source code: 1 , 2 ). 它被编译到完全一样的instanceof做同样的序列(从热点源代码的证明: 12 )。 That is, they both are equal in terms of performance. 也就是说,它们在性能方面是平等的。

foo instanceof Bar should be faster. foo instanceof Bar应该更快。

You can use Bar.class.isInstance(foo) if it's not clear at compile time which class you have. 如果在编译时不清楚拥有哪个类,则可以使用Bar.class.isInstance(foo)

consider the following: 考虑以下:

void test(Object o1, Object o2) {
   o1.getClass().isInstance(o2);
}

In this exsample the JVM decides at runtime which class calls the method. 在此示例中,JVM在运行时确定哪个类调用该方法。 With instanceof this is not possible. 使用instanceof不可能。

So if you know the class at compile time you should use instanceof 因此,如果您在编译时知道该类,则应使用instanceof

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM