Is !(~A && ~B) better than (A||B) in programming?

Arun S R :

I am developing in Java and I am using IntelliJ as my IDE. I wrote an if statement as follows.

if( list1.size() >= 1 || list2.contains(itemX) ) {
    //do something
}

IntelliJ suggested a transformation (DeMorgan's Law) and it transformed it to:

if( ! ( list1.size() < 1 && !( list2.contains(itemX) ) ) ) {
    //do something
}

So it applied a very common discrete mathematics theory on simplifying boolean expressions. What I am wondering is how does this optimize anything?

|| operator anyways does not execute the whole condition if the first part is itself true, and only executes the RHS only if the first part is false.

Is the transformed condition effective? How?

Tejaswini Nanaware :

Both are exactly the same statements.

I agree that OR operator does not evaluate the second part if the first part is TRUE, however, it is also true that the AND operator does not evaluate the second part if the first part is FALSE.

In fact, it will take more time and space to evaluate the ~(~A && ~B) as opposed to A||B.

Hope this helps :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127340&siteId=1