Does the order of cases matter in PHP switch statements? - php

In PHP switch statements, does placing more common cases near the top improve performance?
For example, say the following function is called 1,000 times:
<?php
function foo_user ($op) {
switch ($op) {
case 'after_update':
//Some Stuff
case 'login':
//Some other Stuff
}
}
If in 990 of the 1,000 of the times the function is called the $op argument is 'login', would performance improve by having case: 'login' above case 'after_update': in the switch statement? For example, would the code after case 'after_update': be ignored if $op = login was passed?
I've run some informal tests on this idea, but the difference has been negligible -- perhaps because the code after case: 'login' and case 'after_update': are both trivial. I'd prefer to avoid setting up a more extensive test with non-trivial operations if someone knows the answer outright.
This is specifically a Drupal question, but I imagine it could be addressed by anyone who is familiar with optimizing PHP.

This is likely going to be called a micro optimisation. I don't believe there would be a large difference.
However, order does mean a lot to the logic of the switch case if you allow the cases to fall through, example
switch ($var) {
case 0:
case 1:
do_it();
break;
case 2:
do_it_else();
break;
}
The order is important, the case will fall through and execute any code until it hits a break.
I wouldn't be concerned about the speed of the switch case, unless you had say 100 possible cases. But if then, it'd be likely you should refactor your code.

You will need a whole lot more than 1000 cases to notice a difference, but yes, there is a difference. I wrote up a test:
function test_switch($value) {
$startTime = time() + microtime();
for ($i = 0; $i < 10000000; $i++) {
switch($value) {
case "abcdefg":
$j = $j + 1;
break;
case "hijklmno":
$j = $j + 1;
break;
}
}
$endTime = time() + microtime();
echo "Total time for argument $value: " . ($endTime - $startTime) . "<br>\n";
}
test_switch("abcdefg");
test_switch("hijklmno");
That is 10 million executions of the switch statement. The output is:
Total time for argument abcdefg: 3.99799704552
Total time for argument hijklmno: 5.38317489624
So there is a difference, but it won't be noticeable until you reach on the order of 10 million executions, depending on your processor of course.

If you do not use break; to close each statement PHP will continue to evaluate cases until the end of the switch block which may impact performance in a large enough block. The order then becomes important for getting the behavior you are looking for.
From PHP.Net:
The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
I would caution against relying on this behavior though and use break; for each case as that will remove some ambiguity when you revisit the code later.

Usually, it's recommended to write the most likely case first, the second one next...
but like Alex wrote,
This is likely going to be called a
micro optimisation. I don't believe
there would be a large difference.

Related

Would someone give an explanation of this PHP switch block?

I'd like to ask what this code is doing, and if someone could explain to me with comments?
I am trying to understand what it is doing. I am guessing it switches between them depending on the result of the statements E.g. 2 < 1 and 2 > 1. Then it is setting the dates in a year month day format?
Am I on the right track?
switch (true) {
case ($UserBirthday < $CurrentDate2) :
$CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
break;
case ($CurrentDate2 < $UserBirthday) :
$UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
break;
}
$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1;
Also, can I change it to an if/else statement like this?
if ($UserBirthday < $CurrentDate2) {
$CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
}
else if ($CurrentDate2 < $UserBirthday) {
$UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
}
$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1;
While there doesn't appear to be any benefit from using switch over if..elseif..else statements in your code example, switch is often used in place of long, ugly if..elseif..elseif..elseif..etc. statements. I suspect this is what the author of your code example was modeling.
You can read about switch's many uses at http://phpswitch.com/.
Actually, I've changed my mind, there is nothing wrong with this code, albeit maybe a bit confusing.
Normally you would pass a variable into the switch statement and compare its values in the cases:
switch($a) {
case 1:
// some code
break;
}
In this case, they are basically only checking if something is true, so they pass true into the switch and then each case is a logic statement.
Either way, whatever is passed into the switch is compared with a == against what is in each case. Since switch is useful for large sets of if/else it is valid to use in this case if they wanted to.
However, since they used it in a way that most developers may not be familiar with, it can be confusing and some additional commenting might be wise.
But again, I was wrong, there actually isn't anything wrong with this code.

PHP switch case - flawed or valid? [duplicate]

This question already has answers here:
Why was the switch statement designed to need a break?
(9 answers)
Closed 8 years ago.
I don't understand why a switch-case statement requires you to explicitly insert a break after each case. Isn't the whole point of it to stop once a case is made?
Can someone give me a circumstance where a case is found true but for some reason [you insert reason here] you still need the code block to execute through.
This is a vaild PHP switch-case statement
switch ($error) {
case 'empty':
$msg = 'Field cannot be empty.';
break;
case 'invalid':
$msg = "Field may only contain number.";
break;
}
This is a invaild PHP switch-case statement
switch ($error) {
case 'empty':
$msg = 'Field cannot be empty.';
case 'invalid':
$msg = "Field may only contain number.";
}
So is this break useless or does it serve a purpose in some situations?
Because that's just how it works - it's how the language was designed. Probably because that's how C did it.
The most common use is for two cases to be treated the same.
switch ($error) {
// Treat warnings and errors the same
case 'warning':
case 'error':
echo "Something went wrong.";
break;
}
I believe this question is a duplicate to this one, answered robustly by #Micahel Burr :
Many answers seem to focus on the ability to fall through as the reason for requiring the break statement.
I believe it was simply a mistake, due largely because when C was
designed there was not nearly as much experience with how these
constructs would be used.
Peter Van der Linden makes the case in his book "Expert C
Programming":
We analyzed the Sun C compiler sources to see how often the default
fall through was used. The Sun ANSI C compiler front end has 244
switch statements, each of which has an average of seven cases. Fall
through occurs in just 3% of all these cases.
In other words, the normal switch behavior is wrong 97% of the time.
It's not just in a compiler - on the contrary, where fall through was
used in this analysis it was often for situations that occur more
frequently in a compiler than in other software, for instance, when
compiling operators that can have either one or two operands:
switch (operator->num_of_operands) {
case 2: process_operand( operator->operand_2);
/* FALLTHRU */
case 1: process_operand( operator->operand_1);
break; }
Case fall through is so widely recognized as a defect that there's
even a special comment convention, shown above, that
tells lint "this is really one of those 3% of cases where fall through
was desired."
I think it was a good idea for C# to require an explicit jump
statement at the end of each case block (while still allowing multiple
case labels to be stacked - as long as there's only a single block of
statements). In C# you can still have one case fall through to another
- you just have to make the fall thru explicit by jumping to the next case using a goto.
It's too bad Java didn't take the opportunity to break from the C
semantics.
It's also used for combinatory conditions.
To give a somewhat useless example:
// manually total up a number by 1
$sum = 0;
switch ($number) {
case 4:
$sum += 1;
case 3:
$sum += 1;
case 2:
$sum += 1;
case 1:
$sum += 1;
}
This sets switch apart from exclusive if trees in that one case can be a superset of another, and reduces code duplication. If all your cases contain a break, then you can certainly transpose it into an if list. (switch is often just utilized for stylistic reasons).
A single statement can carry multiple case labels, as the following example shows where we are not using break:
switch($constant)
{
case 'a' :
case 'b' :
case 'c' :
case 'd' :
case 'e' :
case 'f' : hexcvt(c);
}
In this example, if constant-expression equals any letter between 'a' and 'f', the hexcvt function is called.

What is the difference between Switch and IF?

I know this may be simple question but want to know every ones opinion on this.
what is the difference between switch and IF function in PHP?? What I can see is where ever "switch" function uses "IF" function also applies there..correct me if I am wrong..
Or any performance wise difference between two??
Or any performance wise difference between two??
Forget about the performance difference on this level- there may be a microscopic one, but you'll feel it only when doing hundreds of thousands of operations, if at all. switch is a construct for better code readability and maintainability:
switch ($value)
{
case 1: .... break;
case 2: .... break;
case 3: .... break;
case 4: .... break;
case 5: .... break;
default: .... break;
}
is mostly much more clean and readable than
if ($value == 1) { .... }
elseif ($value == 2) { .... }
elseif ($value == 3) { .... }
elseif ($value == 4) { .... }
elseif ($value == 5) { .... }
else { .... }
Edit: Inspired by Kuchen's comment, for completeness' sake some benchmarks (results will vary, it's a live one). Keep in mind that these are tests that run 1,000 times. The difference for a couple of if's is totally negligeable.
if and elseif (using ==) 174 µs
if, elseif and else (using ==) 223 µs
if, elseif and else (using ===) 130 µs
switch / case 183 µs
switch / case / default 215 µs
Conclusion (from phpbench.com):
Using a switch/case or if/elseif is almost the same. Note that the test is unsing === (is exactly equal to) and is slightly faster then using == (is equal to).
If you have simple conditions, like if something equates to something else, then a switch is ideal.
For example, instead of doing the following:
if($bla == 1) {
} elseif($bla == 2) {
} elseif($bla == 3) {
} etc...
It's better to do it like this:
switch($bla) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
break;
}
Alternatively, if you have complex conditions, you should use an if/else.
I think that this is all a matter of opinion though - some people just don't use switch statements at all, and stick with if/else.
No, you are right.
There are not much difference between these statements.
You may use one you like.
Just bear in mind that if you have to use more than 3-4 consecutive conditions - that means you most likely have design faults.
Usually you can substitute such a statement with a loop or with more clear application design.
The Switch Case Statement is an alternative to the if/else statement, which does almost the same thing. The Switch Case Statement executes line by line or statement by statement in other words, and once PHP finds a case statement that evaluates to true, it executes the code corresponding to that case statement.
The fundamental difference between if/else and switch statements is that the if/else statement selects the execution of the statements based upon the evaluation of the expression in if statements, but the Switch Case Statement selects the execution of the statement often based on a keyboard command.
Don't forget, though, that a switch does not necessarily work as a simple if statement. Remembering that a switch does not require a break at the end of each case and leaving that break off allows you to 'fall through' to the next case, too, can allow some interesting and somewhat complex 'ifs'.

Loops within Switch statement

my switch statement has about ten outcome, but some of them need 1/2 loops to check, so i can't write them within case(condition), so i've tried using more than one default case, is this possible?
<?php
switch(true) {
case 1:
break;
case 2:
break;
default:
echo "this text is never printed ??";
while(true) {
while(true) { // case 3
break 3;
}
break;
}
while(true) {
// case 4
break 2;
}
case 5:
break;
default:
while(true) {
// case 6
break 2;
}
case 7:
break;
}
?>
is this sort of thing possible, as my first default doesn't seem to be executing at all?!
thanks
You cannot have more than one default in a switch statement. Also, default should be at the end of of the switch after all the case statements.
What might be happening when your code is run through the PHP engine is that the parser is reading the switch statements into a hash map type data structure and each time the parser finds a default label, it's overwriting the existing entry in the hash map. So only last default label ends up in the data structure that gets used in execution.
No this isn't possible, you can't have more than one default case in a switch statement, you'll need to put additional logic into the single final case statement.
when the default case is reached it captures all conditions so later cases are not evaluated.
To answer your question - no, it is only possible to have one default and that at the end. I'm not sure whether you can place other cases after the default, but what I'm sure of is that they would never be reached...
EDIT:
Also, I don't see what you're trying to do there. What's the point? Could you explain a bit? We might be able to help you accomplish what you want to do
You can have only one default in a switch. Remember that Zend is not the only thing that parses PHP, you may confuse other parsers by not putting the default case as the very last part of the switch.

PHP Coding styles return; in switch/case

we're trying to implement new coding style guidelines for our team, the php codesniffer is printing an warning on switch case statements when no "break" is found like:
switch ($foo) {
case 1:
return 1;
case 2:
return 2;
default:
return 3;
}
is there any good reason to use :
switch ($foo) {
case 1:
return 1;
break;
}
?? the break is never reached ?
It's perfectly valid to leave out the break when you return from a switch.
But it's fairly common practise to add explicit breaks to every case as a defensive programming practise.
switch ($foo) {
case 1:
return 1;
break;
case 2:
return 2;
break;
}
The idea is that should you later change your code in case 1 and remove the return statement, you could forget to add a break.
That would accidentally cause program flow to fall through to case 2.
switch ($foo) {
case 1:
somethingDifferent();
case 2:
return 2;
break;
}
Falling through case statements is slightly unusual and you should add a comment to your code when you do it to show that it's intentional.
switch ($foo) {
case 1:
somethingDifferentAndWeWantToDoCase2AsWell();
// fallthrough
case 2:
return 2;
break;
}
As with many defensive programming practises you've got to balance whether the code bloat - which potentially clutters your code and make it less readable - is worth it or not.
If your "php codesniffer is printing a warning" try to get another better codesniffer and don't forget to try to use the last PHP stable version. You can, of course, write a breakafter one return, but it doesn't make sense, because it will never be read at all. Your code is OK.
Look at this:
$fun = function(int $argument): string {
switch ($argument) {
case 1:
return "one";
case 2:
return "two";
default:
return "more than two";
}
};
$str = $fun(4); // return "more than two"
In my opinion, this is simpler and better: fewer lines => less code to maintain :-)
To answer your question, no there's no good reason to have something that does nothing. Think about it this way, a comment after the return instead of a break saying "don't forget" will have the same affect - none. And put that way it sounds silly, right?
Unless you need to set a var to use later, I'd suggest the approach you have is perfectly fine. I knew the code's intent within 2 seconds from looking at it. Having a break just creates confusion.
There is no one size fits all really. The correct approach depends on whichever fits the scenario. Set a variable in each case and having a break may be the right way, or perhaps just return makes sense.
Some observations on other suggestions made in answers:
1) Not having a break after return means problems could arise if code is later changed
Whenever possible, code should be explicit, as well as readable and clear. We can also code in a way to make future changes easier. But in something as simple as a switch it should be no problem and need no safety net to refactor a case later to add or remove a return or break.
In fact, if you removed a return and "didn't notice there was no break" then that's a poor mistake and could be made in any part of coding. No gotcha checking will save you from that. And one should be very careful coding for future potentials, as that potential may never happen, or something else may happen, and you just end up maintaining obsolete code for years.
In the same vein this was argued to be a safety net for future changes - What if you remove the return and accidentally left in that safety net break when you should have removed it?
Even if this switch statement was a life or death scenario, really serious code, I would be against adding the "pointless" break after the return. Just make sure whoever was working on the code knew what they were doing, and it was code reviewed by enough eyes and tested fully.
If it was that serious, then you'd have additional checks in place better than a proposed safety net to catch sloppy devs.
To argue that break after return adds a safety net, means you're not coding or testing properly. If this is a safety net deemed useful then it's likely there are tons of bugs in the code in potentially more serious places.
The wiki article of "Defensive Programming" was linked to, but it's not relevant here:
Defensive programming is a form of defensive design intended to ensure
the continuing function of a piece of software under unforeseen
circumstances.
Leaving a safety net break in is not a scenario of unforeseen circumstances, nor defensive programming. It's just bad coding, and you can't litter your code with back up code just in case you don't code correctly when you change something. That's such a bad approach to coding. The argument that "if someone removed return it won't work", well you could also have a typo in the case var, or forget to write the case, or...
The return returns, and you don't code "defensively" to avoid a return failing. That would mean PHP is broken, and you aint gonna fill your code with safety nets to cater for that. That's something you have on a much higher level up.
2) break after return keeps it explicit
But it's explicitly wrong. The return returns, so the break won't happen. To me that is scratch head time wondering if I've missed the intent - not for long as it's clear what will happen, but there will be a moment where I ponder it to make sure I've not missed something.
While it's not invalid or error to have a return and then break in the same case, it's just entirely pointless as the break does nothing. It's pointless code that needs to be seen, maintained, and figured out as it's not logical.
If explicit is the core goal and having a break after a return urks you because it's pointless, then I'd say it'd be better to set a variable and break, then return the variable after breaking from the switch.
Like #RageZ answer https://stackoverflow.com/a/1437476/2632129
3) Set a variable and return after the switch statement is completed
There's nothing wrong with this approach at all, but if there's no reason to store the value in a variable (later use etc) then it's good to return immediately when there's no need to hang around to do anything else.
That shows clear intent - return a value as soon as the case is matched.
I have much better solution.Please follow below code for above switch statment:
$result = 3; // for default case
switch ($foo) {
case 1:
$result = 1;
break;
case 2:
$result = 2;
break;
default:
// do nothing
}
return $result;
It will not result in any error and code is also fine with concepts.
I am not an expert in perfect coding but I think the validator would prefer something like that
switch ($foo) {
case 1:
$ret = 1;
break;
case 2:
$ret = 2;
break;
default:
$ret = 3
}
return $ret
I think using return in case statement to break the flow of the code is not really a best practice. So that's why the validator say there is no break ...
For your question about at category, I don't know ... sorry
From the PHP manual (http://us3.php.net/manual/en/control-structures.switch.php) :
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

Categories