[英]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? 为什么?
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.