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

后端 未结 7 1721
小蘑菇
小蘑菇 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.

    0 讨论(0)
  • 2021-02-07 12:10

    I guess the code in java.lang.String supports my answer:

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                        return false;
                }
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2021-02-07 12:11

    One good comparison can be:

    private static String EXAMPLE = "Example";
    private String obj = null;
    

    case 1:

    if(obj.equals(EXAMPLE) {
    }
    

    This is throw null pointer exception..

    case 2 :

    if(EXAMPLE.equals(obj)) {
    }
    

    This will not throw null pointer exception..

    0 讨论(0)
  • 2021-02-07 12:18

    If we compare CONSTANT key(Left side of equals method) with any Object(Right side of equals method) then compiler can do check comparison and give the expected result, but if we do vice versa Object((Left side of equals method)) comparison with Constant key((Right side of equals method)) then your program might through the NULL POINTER EXCEPTION.

    public static void main(String[] args) {
        String CONSTANT_KEY = "JAVA";
        String string = null;
    
        // CASE 1
        if (CONSTANT_KEY.equals(string)) {
            System.out.println("I am in if block");
        }
    
        // CASE 2   
        if (string.equals(string)) {
            System.out.println("I am in if block");
        }
    }
    

    In above code case 1 is always safe to compare the objects to avoid NULL POINTER EXCEPTION instead of case 2.

    0 讨论(0)
  • 2021-02-07 12:19

    Made a simple test with Strings:

    final String constHello = "Hello";
    final int times = 1000000000;
    
    long constTimeStart = System.nanoTime();
    
    for (int i = 0; i < times; ++i) {
        constHello.equals("Hello");
    }
    
    long constTimeStop = System.nanoTime();
    
    System.out.println("constHello.equals(\"Hello\"); " + times + " times: " + (constTimeStop - constTimeStart) + " ns");
    
    
    constTimeStart = System.nanoTime();
    
    for (int i = 0; i < times; ++i) {
        "Hello".equals(constHello);
    }
    
    constTimeStop = System.nanoTime();
    
    System.out.println("\"Hello\".equals(constHello); " + times + " times: " + (constTimeStop - constTimeStart) + " ns");
    

    Edit: As mentioned in the comments below, this wasn't a good way of doing micromeasurements. Switching which part of the code which was going to be executed first proved that warm up time played a significant role here. The first test always runs slower. Repeating the test multiple times in the same code to quickfix this makes the results more or less the same.

    0 讨论(0)
  • 2021-02-07 12:21

    For me its not a speed issue, its a relability issue.

    e.g.

    "Hello".equals(a); // will never throw a NPE
    a.equals("Hello"); // can throw an NPE.
    

    You may prefer it to blow up when a is null but usually I don't.

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