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?<
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 if
s 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 if
s 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 if
s 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 if
s. Rather focus on what the if
s are asking about, or what happens depending on whether they return true or false.
Hope it helps.