Design questions aside, what performs faster on modern JVMs?
foo instanceof Bar
or
Bar.class.isInstance(foo)
Why?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With