"Equality test with boolean literal" - Difference between testing boolean and using ==
codepro, coding-style, java
Solution
For the more direct boolean expression:
boolean valid = true;
if(valid) {
}
The following byte code is generated:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 6
6: return
Whereas with the expanded comparison:
boolean valid = true;
if(valid == true) {
}
The following byte code is generated:
0: iconst_1
1: istore_1
2: iload_1
3: iconst_1
4: if_icmpne 7
7: return
I doubt `ifeq` and `if_icmpne` differ in execution speed, so the additional cost of `if(valid == true)` is really just the extra constant value, which is negligible.
To summarize, there is real no performance difference, and CodePro is flagging your code as a best practice alone.
Problem
I am using Code Pro to review my application code and the tool reported back with the message: Warning: equality test with boolean literal For this code: ``` boolean valid; if(valid == true) ``` which can be fixed by using: ``` if(valid) ``` I have 2 questions on my mind: - Is it just a good coding practice ? - Is there any other benefit in terms of memory optimization or performance optimization ?