How instanceof is implemented inside JAVA?

前端 未结 3 568
梦谈多话
梦谈多话 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
    

提交回复
热议问题