Is CONSTANT.equals(VARIABLE) faster than VARIABLE.equals(CONSTANT)?

后端 未结 7 1713
小蘑菇
小蘑菇 2021-02-07 11:43

I had an interesting conversation with one of my team mate.

Is CONSTANT.equals(VARIABLE) faster than VARIABLE.equals(CONSTANT)in Java?

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 12:07

    Interesting question. Here is the test I wrote:

    public class EqualsTest {
        public static String CONST = "const";
        public void constEqVar(String var) {
            CONST.equals(var);
        }
        public void varEqConst(String var) {
            var.equals(CONST);
        }
    }
    

    Then I compiled it using javac: javac EqualsTest.java and disassembled it using javap: javap -c EqualsTest.

    Here is the relevant snippet of javap output:

    public void constEqVar(java.lang.String);
      Code:
       0:   getstatic       #2; //Field CONST:Ljava/lang/String;
       3:   aload_1
       4:   invokevirtual   #3; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
       7:   pop
       8:   return
    
    public void varEqConst(java.lang.String);
      Code:
       0:   aload_1
       1:   getstatic       #2; //Field CONST:Ljava/lang/String;
       4:   invokevirtual   #3; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
       7:   pop
       8:   return
    

    As you can see the only difference between theses 2 methods is order of operations: getstatic and then aload_1 in first case and aload_1 + getstatic in second case.

    Pretty obvious that the execution time should not depend on this order.

    The only reason to prefer const.equals(var) rather than var.equals(const) is to avoid NullPointerException.

提交回复
热议问题