Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's faster: instanceof or isInstance?

Design questions aside, what performs faster on modern JVMs?

foo instanceof Bar

or

Bar.class.isInstance(foo)

Why?

like image 419
artspb Avatar asked Oct 26 '25 01:10

artspb


2 Answers

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.

like image 180
apangin Avatar answered Oct 27 '25 14:10

apangin


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

like image 45
Dimitrios Begnis Avatar answered Oct 27 '25 14:10

Dimitrios Begnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!