4

Design questions aside, what performs faster on modern JVMs?

foo instanceof Bar

or

Bar.class.isInstance(foo)

Why?

artspb
  • 1,127
  • 1
  • 10
  • 19
  • 2
    #1. It's built into the language. You're not going to get better than that. – Louis Wasserman Apr 05 '16 at 19:45
  • 8
    It almost never matters what's faster. – biziclop Apr 05 '16 at 19:46
  • @LouisWasserman I'm not trying to do better, I'm just curious which operation is faster. – artspb Apr 05 '16 at 19:48
  • 1
    It's practically impossible to tell without measuring. `Class.isInstanceOf()` is an intrinsic method in OpenJDK (and possibly in every modern VM), meaning that it's as fast as possible. `instanceof` on the other hand has its own bytecode operation, so it can potentially be even faster. How calls to each is optimised by Hotspot is another matter. – biziclop Apr 05 '16 at 19:53
  • As for it not being a duplicate, the question may be different, but the answer is the same. If you want benchmark data, the most reliable thing is to write your own [microbenchmark](http://openjdk.java.net/projects/code-tools/jmh/), as any published benchmark data can easily be obsolete or not apply to your specific environment. – biziclop Apr 05 '16 at 20:27
  • 3
    `Class.isInstance` is JVM intrinsic. It is compiled to exactly the same sequence as `instanceof` does (the proof from HotSpot source code: [1](http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/b5b3db42efca/src/share/vm/opto/library_call.cpp#l3568), [2](http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/b5b3db42efca/src/share/vm/opto/graphKit.cpp#l2840)). That is, they both are equal in terms of performance. – apangin Apr 05 '16 at 21:03
  • @apangin That's exactly what I wanted to know. Thank you! – artspb Apr 05 '16 at 21:08

2 Answers2

17

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.

apangin
  • 92,924
  • 10
  • 193
  • 247
1

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

Dimitrios Begnis
  • 823
  • 6
  • 16