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

前端 未结 6 1077
礼貌的吻别
礼貌的吻别 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:48

    If-clauses are some of the cheapest operations there are, performance-wise.

    However, what you put in the if-clause can be really slow.

    For instance, if (true) { ... } is going to be extraordinarily fast, but a single if (calculatePi()) { ... } is going to take literally forever. The if itself is so fast that you'll never have to worry about it, and besides, pretty much everything else you do involves a number of ifs anyway, for example when you do for or while loops or switch statements. All of those intrinsically contain if (one or more) within them.

    As for design, a lot of ifs may be confusing to other developers, depending on what you're writing and how it's written. Sometimes you're better off using switch/case statements or some other application workflow, but to tell you the truth, a bunch of ifs is probably going to perform faster than any sort of structure you may come up with. But only take that to heart if your only concern is performance. Designing software is not, I repeat, not primarily about performance. Good software design is about other things like maintainability, i.e. how easy it is to read and successfully upgrade your code.

    In short, if you're optimizing for performance, don't bother trying to reduce the number of ifs. Rather focus on what the ifs are asking about, or what happens depending on whether they return true or false.

    Hope it helps.

提交回复
热议问题