Java – “equality test with Boolean text” – test the difference between Boolean values and usage==

See English answers > Boolean checking in the 'if' condition 10

For this Code:

boolean valid;
if(valid == true)

You can use the following methods to repair:

if(valid)

I have two questions:

>Is this just a good coding practice? > Are there any other benefits in memory optimization? Performance optimization?

Solution

For more direct Boolean expressions:

boolean valid = true;

if(valid) {
}

Generate the following bytecode:

0: iconst_1      
1: istore_1      
2: iload_1       
3: ifeq          6
6: return

And expand the comparison:

boolean valid = true;

if(valid == true) {
}

Generate the following bytecode:

0: iconst_1      
1: istore_1      
2: iload_1       
3: iconst_1      
4: if_icmpne     7
7: return

I doubt ifeq and if_ The execution speed of icmpne is different, so the additional cost of if (valid = = true) is actually just an additional constant value, which can be ignored

In short, there are virtually no performance differences, and codepro marks your code as a separate best practice

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>