Reputation: 135
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.
Upvotes: 0
Views: 3572
Reputation: 442
They both are the same and should not affect the performance. They are equivalents of each other according to De Morgan's Law.
Upvotes: 3
Reputation: 2263
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.
Upvotes: 3