"Equality test with boolean literal" - Difference between testing boolean and using == [duplicate]

StackOverflow https://stackoverflow.com/questions/15583415

  •  29-03-2022
  •  | 
  •  

Pregunta

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:

  1. Is it just a good coding practice ?
  2. Is there any other benefit in terms of memory optimization or performance optimization ?
¿Fue útil?

Solución

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.

Otros consejos

I would say that it is more of a good practice. One, the code is more compact. And two, the code reads more like natural language.

I have not idea if there is any benefit one way or the other. My guess is that the Java compiler is so mature, that both options perform about the same.

Is it just a good coding practice ?

Yes. Two reasons:

  • The b == true idiom is verbose and linguistically ugly. (Would you ask, "is it true that the Pope is Catholic?" or "is the Pope Catholic?" ... ?)

  • The b == true idiom is the one any only case in Java that can be miss-written as b = true.

Is there any other benefit in terms of memory optimization or performance optimization?

Almost certainly not.

When the two bits of code result in different bytecodes, it is most likely that the JIT compiler will turn them into either the same native instruction sequences, or sequences that have identical performance. (If not, then the optimizer is "missing a trick").

Either way, the difference is likely to be too small to be too small to be significant.

There is no difference in behavior, and while I can't speak authoritatively for every JVM it is difficult to imagine that there would be any performance difference to speak of.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top