I'll build on top of @James answer:
public class TestNull {
public void left(String s) {
if (s == null);
}
public void right(String s) {
if (null == s);
}
}
bytecode:
public class TestNull {
....
public void left(java.lang.String);
Code:
0: aload_1
1: ifnonnull 4
4: return
public void right(java.lang.String);
Code:
0: aconst_null
1: aload_1
2: if_acmpne 5
5: return
}
First is faster (when null
is on the right hand side) because java has a bytecode command ifnonnull
which compares the loaded variable with null.
Second is slower because another command is being used: if_acmpne
and it compares the loaded aconst_null
which it sees as a constant.
Apparently if_acmpne
is slower than ifnonnull
:
if_acmpne
pops the top two object references off the stack and
compares them. If the two object references are not equal (i.e. if
they refer to different objects), execution branches to the address
(pc + branchoffset), where pc is the address of the if_acmpne opcode
in the bytecode and branchoffset is a 16-bit signed integer parameter
following the if_acmpne opcode in the bytecode. If the object
references refer to the same object, execution continues at the next
instruction.
ifnonnull
pops the top object reference off the operand stack. If the
object reference is not the special null reference, execution branches
to the address (pc + branchoffset), where pc is the address of the
ifnonnull opcode in the bytecode and branchoffset is a 16-bit signed
integer parameter following the ifnonnull opcode in the bytecode. If
the object reference on the stack is null, execution continues at the
next instruction.
So if (s == null)
must be faster (opposite to what OP stated in the question).