Now I'm writing an ORM Framework and very care about performance.
In this Framework , I have to use instanceof
and Class.isAssignableFrom
to check type compability.
So I have a little doubt about the performance of instanceof
and Class.isAssignableFrom
How slow exactly it is?
instanceof is supposed to be faster, it's one bytecode operation
public static void main(String[] args) {
boolean res1 = args instanceof Object;
bytecode
ALOAD 0
INSTANCEOF java/lang/Object
ISTORE 1
compare to
boolean res2 = Object.class.isAssignableFrom(args.getClass());
bytecode
LDC Ljava/lang/Object;.class
ALOAD 0
INVOKEVIRTUAL java/lang/Object.getClass()Ljava/lang/Class;
INVOKEVIRTUAL java/lang/Class.isAssignableFrom(Ljava/lang/Class;)Z
ISTORE 2
How instanceof is implemented inside JAVA?
The short answer is that it is platform dependent.
The long answer is that you should be able to find out how it is implemented by writing a test case that uses instanceof
, running it in a loop to ensure it gets JIT compiled, and then dumping and examining the native code.
However, I don't think this is going to be particularly instructive. What you really want to know is whether instanceof
or Class.isAssignableFrom
is faster. You can measure this by careful micro-benchmarking.
FWIW, I predict that you will find that instanceof
is faster. (I expect that the JIT compiler would be able to optimize instanceof
in ways that it couldn't optimize the reflective version.)
But lastly, I'd suggest that you don't waste your time with this level of optimization at this stage. Code this using instanceof
, and wait until you have some profiling data that tells you that your instanceof
usage is really a performance bottleneck. (It is all very well to "care about performance" ... but in reality there are more important things that you need to get right BEFORE performance becomes a key issue.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With