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?<
The question is not about having too many if else statements but 1) the order of them and 2) how efficient your conditions are
1) If else status should be in descending order of probability of the conditions.
In my particular wp_posts
database table, 80% of the records have post_status
of "draft", "pending", "trash" etc. but not "publish". About 40% the records have "post" as post_type
. So, it would make no sense to have
if ($post_type=="post"&&$post_status=="publish") {
doA();
} elseif ($post_type!="post"&&post_status=="publish") {
doB():
} elseif ($post_type=="post"&&post_status!="publish") {
doC();
} else {
doD();
}
but it should goes in reverse order
Regarding 2), the database schema of WordPress suggests that in_category()
will be slow. If it's some query that you write yourself and of course, it depends on how efficient your query is
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.
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.
In a way..YES.
I say this considering a Worst case scenario, in this case a very large model object with lots of conditions. Here, the code has to go through all conditional checking which eventually slows down the code.
Conditional statements pose difficulty for parallelization and vectorization, and a long series of IF-THEN can also cause instruction cache misses and other effects. But if that's what makes the code clearest, then use it.
Very complicated if/else structures indicate a bad design in most cases. You can better focus on improving a bad design than optimization, premature optimization is the root of all evil!.
If you give an example of the type of code you are talking about, it will maybe be possible to give a more detailed answer.
I've just came across an very interesting piece of article from WPShout which uses a very human analogy to invite us to code smarter, and why deeply nested if { .. }
statements might degrade not only performance but also the code maintainability. If the logic is performance aware, without unnecessary bloated iteration checks, chances are you'll end up with a pretty well organized, responsive-cleaner code.
CODE EXAMPLE (extracted form the article)
"Let’s make this concrete by looking at two simple code examples: first in bubble-style, then in gateway-style".
Bad: Bubble-Style
$is_first_thing_working = true;
$is_second_thing_working = true;
$is_third_thing_working = true;
$is_fourth_thing_working = true;
if( $is_first_thing_working === true ) {
if( $is_second_thing_working === true ) {
if( $is_third_thing_working === true ) {
if( $is_fourth_thing_working === true ) {
return 'Working properly!';
}
else {
return 'Fourth thing broken.';
}
}
else {
return 'Third thing broken.';
}
}
else {
return 'Second thing broken.';
}
}
else {
return 'First thing broken.';
}
Good: Gateway-Style
$is_first_thing_working = true;
$is_second_thing_working = true;
$is_third_thing_working = true;
$is_fourth_thing_working = true;
if( $is_first_thing_working !== true ) {
return 'First thing broken.';
}
if( $is_second_thing_working !== true ) {
return 'Second thing broken.';
}
if( $is_third_thing_working !== true ) {
return 'Third thing broken.';
}
if( $is_fourth_thing_working !== true ) {
return 'Fourth thing broken.';
}
return 'Working properly!';
NOTES ON EXAMPLE
The difference between the two code snippets above boils down to a key distinction:
The bubble method asks if important conditions are true, and only runs code if they are true.
The gateway method asks if important conditions are false, and immediately issues exit instructions for each condition if it’s false.
The bubble method forces nesting, because you have to check “true, true, true, true” before you get to the code you want to run. Each “true” check is a level of nesting—a condition your code has to live inside.
The gateway method is not nested:
as you see, the code is never more than one layer of logic deep. This is because once a given gateway is passed, we can forget about it completely. In other words, since we didn’t exit after our $is_first_thing_working
check, we automatically know that $is_first_thing_working
is true for the rest of the code.
"It’s like real life: if you’re sitting next to me in history class, I know you’re a human, a student at my high school, etc.—or else you would’ve never been in my class in the first place. No need to check."