I've always been taught in my first job as a Java Developer to avoid the use of "!=" but instead use an empty if clause then put the logic in the else:
//Bad:
if (x != null) {
// logic
}
//Good:
if (x == null){
} else {
// logic
}
Our lead developer's reasoning was to avoid an unnecessary bit-switch especially for simple logic like null checking.
I've been looking for sources that state this but I can't seem to find any. Is the empty if clause practice really a "best practice" or just a preference?
IMO, this is a failed attempt at micro-optimisation.
Compile the code
public static void main(String... args) {
Object x = null;
//Bad:
if (x != null) {
// logic
}
//Good:
if (x == null){
} else {
// logic
}
}
and check with javap
public static void main(java.lang.String...)
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=1, locals=2, args_size=1
0: aconst_null
1: astore_1
2: aload_1
3: ifnull 6
6: aload_1
7: ifnonnull 10
10: return
LineNumberTable:
line 9: 0
line 11: 2
line 16: 6
line 20: 10
}
Both have a jump to another branch. There is no different in performance. IMO, the readability of your code suffers though.
If x is null, blah, otherwise logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With