Two if conditions or one if with OR
I have a small doubt
I have following code
bool res= false;
if(cond1)
{
res = true;
}
if(cond2)
{
res = true;
}
Instead of this if I put following code
if(cond1 || cond2)
{
res = true;
}
Which code snippet will be more optimized?
I believe it would be second one as I have avoided an If c开发者_开发百科ondition.
Well, I don't know if it's appropriate but: It doesn't matter in this case.
Do not too much of micro-optimizing.
But to answer your question, stick with the readably one.
The fastest solution would be something like this:
bool res = cond1 || cond2;
This is micro-optimization. Pick the one that's more readable :
return cond1 || cond2;
The performance gain will be really unnoticeable but the second one is much more readable and logical than the first one.
The only difference is in cases where cond1 is true - so int the second example cond2 will not be tested. If cond1 is false cond2 will be tested in both cases.
Too bad not everyone sees the difference between an Or (|) and a Condional Or (||). If in the second snippet an Or is used, there is no difference (both conditions are evaluated). Using a Conditional Or, means if the first condition (from left to right) is true, the next isn't even evaluated.
This is a very usefull feature.
2nd option is more optimized. In first option it will always check for cond2. You can change second if to else if in option1 to optimize it.
Here the performance difference will not be noticeable .But definitely the second one is better.
1) The readablity is better for second.
2) second snippet is more logical than first one .
3) If we see IL
with ILDASM
then the number of lines in assembly for the first snippet will be more than that of the second one. So, the code size is more for first snippet. It's better if the size of the assembly is less.
If cond1
and cond2
are not simple booleans but properties or functions with side-effects then there is a difference because in the first version cond2
will always be evaluated and the side-effects will therefor occur.
Assuming each cond
is about equally likely to be true as false, and assuming each cond
takes one STU (significant time unit) then half the time the ||
will take 1 STU and half the time 2 STU, for overall expectation of 1.5 STU instead of 2.
If STU is a nanosecond, it probably doesn't matter.
If STU is a century, it probably does.
精彩评论