How instanceof is implemented inside JAVA?

回眸只為那壹抹淺笑 提交于 2019-12-01 06:06:47

问题


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?


回答1:


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.)




回答2:


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



回答3:


1st of all, if youre going to micro-benchmark this, at least run a large loop and average, because youre seeing a lot of noise in your timing.
having said that, yes, reflection is slow. if you can design around it and use anything else, do it.
for example, if the set of classes you'll work with is small and known in advance, keep them in a Map<Class,[Something]> and look them up there - you'll need all subclasses to be in that map, but the lookup will be much faster than an instanceof (thats basically how a lot of fast serialization libraries avoid reflection)
if you dont want to (of cant) build this map in advance you can build it as a cache at runtime and then you'll need the instanceOf call only once per new class



来源:https://stackoverflow.com/questions/14190189/how-instanceof-is-implemented-inside-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!