How instanceof is implemented inside JAVA?

前端 未结 3 529
梦谈多话
梦谈多话 2021-01-13 22:05

Now I\'m writing an ORM Framework and very care about performance.

In this Framework , I have to use instanceof and Class.isAssignableFrom

相关标签:
3条回答
  • 2021-01-13 22:15

    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
    
    0 讨论(0)
  • 2021-01-13 22:18

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

    0 讨论(0)
  • 2021-01-13 22:18

    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

    0 讨论(0)
提交回复
热议问题