0

I am wondering how costly is to combine logical operators? What is the best way to combine them?

For example: What is the difference between following two statements in terms of optimization?

1) if((!x || !y || !z) && (a != b)) 
2) if(!( x && y && z) && (a != b))

I heard from my peers that you should use ANDing operation more often than ORing operation. I am new to C language. Please someone help me to understand this. Any material or link would also be helpful.

10
  • 1
    Just leave it to the compiler. It's probably more efficient in optimising such stuff. Commented Dec 30, 2016 at 19:40
  • 1
    Bothe are same according to DeMorgan's law. Commented Dec 30, 2016 at 19:40
  • 6
    Please be aware of the short circuit rule for evaluating conditional expressions in C. If the the entire conditional can be known without evaluating further expressions, they are skipped. So beware of any side-effects that you might expect to happen, but do not (may be a value change or a function call). The direct answer is to write the conditional in the clearest way that will be understood the most easily: when you look at it next year. Commented Dec 30, 2016 at 19:41
  • 1
    Compilers are pretty smart. On lowest optimization levels it generates equivalent code, and when higher levels are used, one version is recognized as being equivalent to the other. Commented Dec 30, 2016 at 19:42
  • 1
    You can transform and-expression and to a semantically equivalent or-expression by using negation. If a condition has multiple conditions connected via an and, it can faster be checked since the overall condition is false if at least one of its conditions is false. However, I would focus on readability since this can easily be optimized by a complier. Commented Dec 30, 2016 at 19:45

2 Answers 2

3

Unless this code is in an extremely hot path of your code, always choose the form that is the most logical to a future reader.

If it is in a hot path, compile both and look at the assembly. One good tool that let's you see the output for many compilers and CPUs is godbolt

Here's an example testing your scenario: fiddle

As you can see, the number of instructions are same.

Sign up to request clarification or add additional context in comments.

Comments

3

They both are the same and should not affect the performance. They are equivalents of each other according to De Morgan's Law.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.