开发者

Nested versus composite conditions

Which one of these 2 examples would perform better:

Example 1:

if($condition_1)
{
 if($cond开发者_开发知识库ition_2)
 {
  // do something
 }
}

Example 2:

if($condition_1 and $condition_2)
{
 // do something
}


The difference, if any, will be negligible. You won't have to worry about the second one evaluating both conditions because of short-circuit evaluation

IMO the 2nd form makes the code more readable. I hate seeing a million indents.


This is a serious case of premature micro-optimization. Even if there were a difference, it would be minuscule to non-existant - it's not a question of which one performs better, it's which one is more readable. And that would depend on the specific case. Isolated out of context, though, I would say the second alternative is preferable: an "if" statement implies an "else", even if it's not present, and two "ifs" mislead the reader.


It will be negligible difference if there is one at all. I see brevity there with later approach.


Nested control structures will have more Cyclomatic Complexity. Compare the nested if block construct

Lines of Code (LOC):                                  6
  Cyclomatic Complexity / Lines of Code:           0.40
Comment Lines of Code (CLOC):                         1
Non-Comment Lines of Code (NCLOC):                    5

versus the composite if block structure

Lines of Code (LOC):                                  9
  Cyclomatic Complexity / Lines of Code:           0.25
Comment Lines of Code (CLOC):                         1
Non-Comment Lines of Code (NCLOC):                    8

Note that the number varies on how you layout the code. Writing the nested structure on one line will increase CC to 0.67. Generally speaking, you want to avoid nesting control flow too deep, because it will get harder to maintain.

So, if it's not helping readability, use the combined comparison.

Edit: in case you are wondering why it's nine and six LOCs: because I added <?php and empty lines to the files I used for the analysis


I found the following here:

Evaluation of logical expressions is stopped as soon as the result is known.

So, if you write cond1 and cond2, it stops if cond1 evaluates to false. So it's even no difference in speed.


If it's just one block, go with the later option as it requires less indentation, is shorter and arguably, more readable.

However, notice that from that time, you'll the using a variation of the first because you'll be adding elses. These are obvisouly not the same:

if ($condition_1) {
    if ($condition_2) {
        // do something
    }
    else {
        //do something else
    }
}

if ($condition_1) {
    if ($condition_2) {
        // do something
    }
}
else {
    //do something else
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜