Does having a lot of if statements degrade rendering speed of php?

前端 未结 6 1046
礼貌的吻别
礼貌的吻别 2021-01-02 04:12

I was wondering if complicated if/else structures in my PHP code could be a bad design decision. Does having a lot of if statements make PHP run slow, site load slower etc?<

6条回答
  •  一整个雨季
    2021-01-02 04:50

    Nope. In fact, it'll actually speed it up in most cases (because it's allowed to skip over blocks of code).

    The only time large numbers of if statements will slow it down is if the condition you're checking requires processing. An example would be something like:

    while (true)
    {
        if (count($some_array) == 0) { break; }
        /* some other code */
    }
    

    Ever iteration through the loop checks if count($some_array) == 0. That means that every pass, PHP has to go and manually count the number of items in $some_array because it may have changed. This also applies to the stop condition in a for loop. This is because a for loop can always be rewritten as a while loop:

    for ([INITIALIZER_ACTION]; [CONDITION]; [POST_ITERATION_ACTION]) { [CODE]; }
    

    is the same as...

    [INITIALIZER_ACTION];
    while ([CONDITION]) { [CODE]; [POST_ITERATION_ACTION]; }
    

     

    If you're considering merging a bunch of if statements into one: don't, you won't get any benefits. PHP does short circuiting which means that if it reaches a point where it knows what the outcome will be, it'll skip the rest.

    For example, consider $a = 5; if ($a > 0 || $b > 100 || $c > 200) {}.
    Once PHP sees that the $a > 0 condition is satisfied, the whole statement resolved to true (because of the usage of OR values) and doesn't bother to check $b > 100 or $c > 200.

    So to answer your question: unless you have an ungodly number of conditionals that each require complicated calculations or have side effects, you can usually consider the quantity of them to be inconsequential.
    However, as others have noted, having too many if statements can reduce code readability. In many cases, if you can remove a conditional without it affecting the behavior of the code, then you didn't need it to begin with.

提交回复
热议问题