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

Andrew Haley aph at
Sat Jul 18 13:11:22 UTC 2020

On 15/07/2020 10:08, Christoph Dreis wrote:
> 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?

You need to keep in mind that JMH testing of such extremely small
intervals of time is difficult to do. A single load from L1 cache has
a latency of four or five cycles, so about 1 - 1.3ns. Your
testInstanceOfClass test takes essentially no time at all: that 2ns is
the cost of Blackhole.consume, as you'll see if you try

	public boolean testEmptyMethod(BenchmarkState state) {
        return true;

I getL

Benchmark                       Mode  Cnt   Score   Error  Units
Invoke.testEmptyMethod          avgt    3   5.172 ± 0.019  ns/op
Invoke.testInstanceOfClass      avgt    3   5.175 ± 0.023  ns/op
Invoke.testInstanceOfInterface  avgt    3  13.370 ± 0.303  ns/op

Your microbenchmark here is too micro.  :-)

Andrew Haley  (he/him)
Java Platform Lead Engineer
Red Hat UK Ltd. <>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the hotspot-runtime-dev mailing list