Performance of instanceof with interfaces is multiple times slower than with classes

Sergey Kuksenko sergey.kuksenko at oracle.com
Fri Aug 7 17:34:37 UTC 2020


By the way. Hotspot has CHA (class hierarchy analysis) which works for 
classes, but didn't work for interfaces.

Particularly for your benchmark:

  "testInstanceOfClass" should be generated into the simple "false" and 
"testInstanceOfInterface" should be generated into real runtime check.

Did you checked generated assembly?


On 7/15/20 2:08 AM, Christoph Dreis wrote:
> Hi,
>
> please forgive me if this is a stupid question or a known problem.
>
> I was working on something that involved an instanceof check and needed to change it slightly.
> I was surprised to see that the performance difference between an interface and a class is quite big.
>
> E.g. consider the following benchmark:
>
> @BenchmarkMode(Mode.AverageTime)
> @OutputTimeUnit(TimeUnit.NANOSECONDS)
> @State(Scope.Thread)
> public class MyBenchmark {
>
> 	interface TestInterface {}
> 	private static class TestClass {}
> 	private static class AnotherClass {}
>
> 	@State(Scope.Thread)
> 	public static class BenchmarkState {
> 		private Object clazz = new MyBenchmark.TestClass();
> 	}
>
> 	@Benchmark
> 	public boolean testInstanceOfInterface(BenchmarkState state) {
> 		return state.clazz instanceof TestInterface;
> 	}
>
> 	@Benchmark
> 	public boolean testInstanceOfClass(BenchmarkState state) {
> 		return state.clazz instanceof AnotherClass;
> 	}
> }
>
> Benchmark                                                Mode  Cnt   Score    Error   Units
> MyBenchmark.testInstanceOfClass                          avgt   10   2,085 ±  0,179   ns/op
> MyBenchmark.testInstanceOfInterface                      avgt   10  18,783 ±  0,595   ns/op
>
> I was surprised to see that the interface variant is so much slower.
> Both checks should return false and there is no big hierarchy that needs to be walked up/down.
>
> Could you enlighten me what the cause for this is and maybe point me to the code where this is done?
> Is this maybe even a bug/regression? Can we maybe do something to improve the interface case?
>
> Thanks in advance,
> Cheers,
> Christoph
>
>


More information about the hotspot-runtime-dev mailing list