Due to the benchmarking done in other threads (cf. https://stackoverflow.com/a/397617/1408611) it was shown that instanceof in Java 6 is actually quite fast. How is this achieved?
I know that for single inheritance, the fastest idea is having some nested interval encoding where each class maintains a [low,high] interval and an instanceof is simply an interval inclusion test, i.e. 2 integer comparisons. But how is it made for interfaces (as interval inclusion only works for single inheritance)? And how is class loading handled? Loading new subclasses means that a lot of intervals have to be adjusted.
AFAIK each class knows all the classes it extends and interfaces it implements. These could be stored in a hash set giving O(1) lookup time.
When code often takes the same branch, the cost can be almost eliminated as the CPU can execute the code in the branch before it has determined whether it should take the branch making the cost next to nothing.
As the micro-benchmark was performed 4 years ago, I expect the latest CPUs and JVMs to be much faster.
finally prints
if I change the “doubles” with
I get
Note: If I change
to
the performance was the same.