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

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

提交回复
热议问题