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

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

提交回复
热议问题