问题
Design questions aside, what performs faster on modern JVMs?
foo instanceof Bar
or
Bar.class.isInstance(foo)
Why?
回答1:
Class.isInstance
is JVM intrinsic. It is compiled to exactly the same sequence as instanceof does (the proof from HotSpot source code: 1, 2). That is, they both are equal in terms of performance.
回答2:
foo instanceof Bar
should be faster.
You can use Bar.class.isInstance(foo)
if it's not clear at compile time which class you have.
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.
With instanceof
this is not possible.
So if you know the class at compile time you should use instanceof
来源:https://stackoverflow.com/questions/36435670/whats-faster-instanceof-or-isinstance