I had an interesting conversation with one of my team mate.
Is CONSTANT.equals(VARIABLE)
faster than VARIABLE.equals(CONSTANT)
in Java?
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.