Which is Faster and better, Switch Case or if else if? - php

Which is the better and fastest methods : if or switch ?
if(x==1){
echo "hi";
} else if (x==2){
echo "bye";
}
switch(x){
case 1
...
break;
default;
}

Your first example is simply wrong. You need elseif instead of just else.
If you use if..elseif... or switch is mainly a matter of preference. The performance is the same.
However, if all your conditions are of the type x == value with x being the same in every condition, switch usually makes sense. I'd also only use switch if there are more than e.g. two conditions.
A case where switch actually gives you a performance advantage is if the variable part is a function call:
switch(some_func()) {
case 1: ... break;
case 2: ... break;
}
Then some_func() is only called once while with
if(some_func() == 1) {}
elseif(some_func() == 2) {}
it would be called twice - including possible side-effects of the function call happening twice. However, you could always use $res = some_func(); and then use $res in your if conditions - so you can avoid this problem alltogether.
A case where you cannot use switch at all is when you have more complex conditions - switch only works for x == y with y being a constant value.

According to phpbench.com, if/elseif is slightly faster, especially when using strict comparison (===).
But it'll only really matter if you want to shave off microseconds on a function that'll be called thousands of times.

General rule is use switch whenever the number of conditions is greater than 3 (for readability).
if / else if / else is more flexible (hence better), but switch is slightly faster because it just computes the condition once and then checks for the output, while if has to do this every time.
EDIT: Seems like switch is slower than if after all, I could swear this was not the case...

When using ==, performance of if ... elseif compared to switch is almost identically. However, when using ===, if ... elseif is about 3 times faster (according to: phpbench).
Generally, you should go with what is most readable and use switch when making more than 3 comparisons. If performance is a major concern and you don't need to make any type conversions, then use if ... elseif with ===.

It's depending on usage. If you have fxp status (online, away, dnd, offline...) its better use switch.
switch(status)
{
case 'online':
...
}
But if you wanna something like this
if ((last_reply.ContainsKey(name)) && (last_reply[name] < little_ago))
or
if (msg.ToString()[0] == '!')
its better use if else.

I found this post: https://gist.github.com/Jeff-Russ/2105d1a9e97a099ca1509de1392cd314 which indicates switch/case to be faster than if/elseif with ===.
They also indicate nested if statements which makes a lot more sense and also provide far better results.
Their times:
nested if/elseif === : 0.25623297691345 (NESTED IF)
switch/case : 0.33157801628113 (SWITCH CASE)
if/elseif with === : 0.45587396621704 (FLAT IF)
only if with === : 0.45587396621704 (ONLY IF)

Switch is faster than if because switch uses jump table and jump table is made by compiler during compile time and run by cpu/os. For ex if you have 100 cases and you will get your value in 100 th one so what do you think it will run all 99 conditions...no..it will directly jump to 100th one with the help of jump table..so how can we prove this?...if you write default statement at start and then run the program will you get default value,since it is at start? No..you will get your desired answer because of jump table..it knows where is default and where is your assigned value and it will directly take you to your desired answer..
Talking about which is better...
Every work that can be done in if can be done in switch..
But for lesser condition if is better and for more conditions switch..like upto 3 conditions if is good.. after that a good programmer uses switch..that's all

I belive the compiler will turn them into very similar, or maybe even identical code at the end of the day.
Unless you're doing something weird, don't try and do the optimisation for the compiler.
Also, developer time is generally more important than runtime (with the exception of games), so it'sbbetter to make its more readable and maintainable.

in my opinion the "if/else" is faster but not better than switch
but i prefer this:
echo ($x==1?"hi":($x==2?"bye":""));
if you have to do 1,2 cases like if/else if/else

Related

switch statement having only one case

I only have one case in switch statement
switch ($coreName) {
case 'stock':
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
break;
}
My question is this a good practice or shall I use an if statement for this? Any performance differences or anything?
Use if else Only when :
1. you have only 2 or more conditions OR You have multiple conditions in single if else.
And use switch when
1. You have to compare `ONE` variable value against multiple.
In your case if else is better
Nothing speaks against this from a technical point of view.
So the question to answer is: why did you implement a switch statement instead of an if conditional?
I'd say the default should be an "normal" if condition, unless special reasons point to a switch instead. The two primary reasons might be:
extensibility (for later additions)
readability (for other coders)
Especially the first case should be considered here. If it might become necessary to extend the handling, then certainly using a switch right away is a good practice.
If you go to phpBench.com and scroll down to see the results between if and case, you can see that using an if statement is slightly faster, but the results aren't too different. (Screenshot below)
You may as well use an if as it is easier to read, less code and is still faster (even by only a tiny amount).
if($corename === "stock") {
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
case should only be used when you compare multiple values rather than just one. This is the same as using elseif. Using if is the most suited for this specifically.
Why not simply do a simple if, like this :
if($coreName == 'stock')
{
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
Hope this helps.

If a switch matches multiple cases will all matching cases run?

I'm attempting to go through a large number bitwise tests, 32 to be exact, where there could be multiple matches. The only method I can think of that would work is to use a whole long list of if statements, e.g.
$test = 3;
if(($test & 1) == 1) {
do something...
}
if(($test & 2) == 2) {
do something else...
}
The other possibility I was thinking of to cut down on the code, although probably not by much is a switch statement. That said, I'm not even sure if what I am thinking of will even work:
$test = 3;
switch($test) {
case ((1 & $test) == 1):
do something...
break;
case ((2 & $test) == 2):
//Will this run?
do something else...
break;
}
Will the break end the switch? Or will the switch continue and each case run that the bitwise operation returns true?
I ask because my actual program will have 32 different tests, and I don't want to write all 32 just to find it doesn't work and Google hasn't turned up anything on this.
If this doesn't work is there a solution that will, or am I relegated to a large number of if statements?
No this is not the case. Only one of the switch cases will run in your example. As soon as break is encountered the switch processing ends. Only one branch will match. In PHP I think (but you might want to double check) the first matching case will run.
With multiple possible matches you will need to use a set of if statements (note do not use if...elseif)
I would convert to
if($test & 1) {
// do stuff
}
if(test & 2) {
// do stuff
}
Well first, using switch with int this way is not really recommended. It's not a good practice / not really readable / not comfortable. I would say it does not even work, although I have a doubt now... depending on versions and stuff, I'm not aware enough of these things.
Then, to answer your question, you only go inside the first matching case... then the break makes you leave the switch. However, you can omit the break and it will go through the second case.
Anyway, you should make more use of OOP to characterize better what you intend to do, and things will probably get more simple and clearer.

Is it good practice to use break and continue in PHP?

Is it a good practice to use break and continue as sentinel for loops in PHP?
e.g.
if (!empty($var))
break;
do {
if (condition1)
break;
some code;
some code;
if (condition2)
break;
some code;
some code;
if (condition3)
break;
some code;
some code;
} while (false);
vs.
if (!condition1) {
some code;
some code;
if (!condition2) {
some code;
some code;
if (!condition3) {
some code;
some code;
}
}
Some find the first version an abhomination and difficult to read and love the second version. Some find the first version cleaner and easier to read. As the number of conditions multiply, I tend to find the first version easier to follow, as the second one tends to get more and more difficult to follow the level of nesting. Also if the if (condition) break; gets into something only slightly more complex like if (condition) {some code; break}, the do {if .. break; if .. break..;} while(false) pattern gets even more clear compared with equivalend nested ifs.
In light usage it is ok, but in heavy usage it makes your code spaghetti. break and continue is basically just a restricted goto and as such, use sparingly.
It absolutely is, they're both valid programming constructs.
What is not a good idea is the newly introduced GOTO. (Please tell me this was an April fool's joke I didn't see the note about!)
It is perfectly correct to use break or continue as long as it helps to make the code easier to read and understand. I personally use them very rarely, and only when I cannot easily use another structure.
In the case of most while statements, it's easier to achieve the same result as a break or continue by using a boolean variable as the condition for the loop in the first place, and then modifying its value inside the loop.
On the other hand, the best use case for the break, in my opinion, is to save resources if you are iterating through an array or something similar with a for or foreach block and are only interested in processing elements until some item is reached. By using a break after reaching this element, it is possible to save on processing power by breaking out of the loop without going over the remaining elements. This makes the code more efficient without making it less legible.
And of course, it is practically impossible to use switch statements without break.
Another exception is if you need to control nested structures, in which case it is sometimes simpler to use break n or continue n than manipulate multiple variables concurrently. (Even though this use case is probably the most controversial...)
In Python, we use infinite loop and break to improve readability. So yes, you can use it, provided you do it correctly, and for a good reason.
Let me answer with a couple of questions:
Why shouldn't it be considered good practice?
Does it reduce readability of your code?
Does it slow down your for cycles?
For a discussion of break and continue in PHP (and looping in general) have a look at Advanced loops - you get the impression that the author can just about manage to swallow break and continue but not break n and continue n. :-)
In 5+ years programming PHP I never had to use break outside of switch statements.
Continue is sometimes used to skip first or last items in iterations, but I don't like it very much.
Why did they reintroduce GOTO ? that's a shame
To answer the question, in
if (!empty($var))
break;
Why not use return (if in a method context)
if (!empty($var))
return false;
I think this way much clear and makes the caller aware of what's happened inside. A better use for argument errors is using Excecptions, which in facte will break execution a the point they are raised.

What is faster: many ifs, or else if?

I'm iterating through an array and sorting it by values into days of the week.
In order to do it I'm using many if statements. Does it make any difference to the processing speed if I use many ifs, versus a set of else if statements?
Yes, use an else if, consider the following code:
if(predicateA){
//do Stuff
}
if(predicateB){
// do more stuff
}
of
if(predicateA){
//
}
else if(predicateB){
//
}
in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.
I doubt that a micro optimization like this will make a measurable difference in your code.
Your sorting algorithm is more likely to be the source of a performance problem. Which sorting algorithm you choose will be critical, not many "ifs" versus "else if".
UPDATE:
The points made by others about "else if" being a better choice, due to its early exit and exclusive logic characteristics, suggest that it should be preferred over "if" in this case.
But the point about algorithm choice still stands - unless your data set is very small.
It's obvious that O(log n) would be better than O(n^2), but size of dataset matters as well. If you have only a few elements, you might not notice the difference. In that case, coding an inefficient method in the cleanest, most readable, most easily understandable at a glance could be your best bet.
You can have a look at phpbench
But to be honest if you want to optimize at this level, you might want to learn something else than php.
To be honest I don't think it would matter which way you do it in terms of performance, I doubt you would see any difference. I would recommend using a switch statement which isn't a performance enhancment, simply syntactically nicer:
switch ($day)
{
case "Monday":
// do something with Monday
break;
case "Tuesday":
// do something with Tuesday
break;
case "Wednesday":
// do something with Wednesday
break;
}
I made a benchmark if there's a true difference between successive if() and if() then a few elseif()
I put a big string and did about 20 strpos() each time (x100 000) with the two methods and it showed this result :
Try 1 : 0.5094 (including elseif)
Try 2 : 0.6700 (including only if)
There's no doubt. I already knew sucessive elseif() were faster, even though there's a return in the middle ; it's still good to put some statistics in the answer.
else if would be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of the ifs.
Also consider reordering the compares in order of descending frequency.
And using the switch statement depending on the datatype of the object you are comparing.
However at this point, as duffymo has suggested, you would be micro optimizing. The performance gain will never be as significant if you haven't chosen the right sorting algorithm for the job first.
If the values are integers you may achieve an optimisation by using a table lookup. E.g. say you have 256 values that map into 7 days somehow, you could set up an array with 256 cells and each cell contained the day of week you wanted. Then instead of:
if ( value == 0 ) {
dayofweek = 1;
} else if ( value == 1 ) {
dayofweek = 2;
} else if ( value == 2 ) {
dayofweek = 3;
} else if ...
.. you could have..
dayofweek = lookuparray[value];
Of course, if you use this technique, then you should check the bounds of value first.
I would put another vote in for opting for a switch() statement instead.
This question is specially interesting when the if block returns thus finishing the method. It also applies directly to the way comparators in Java work.
I've thus run each method (bellow) 250.000.000 times and the results are as follows:
two values if/else - 6.43 millis
three values if/else/if - 8.66 millis
three values if/if - 9.01 millis
While the worst case takes 1.4 times longer than the best one do notice that this is the aggregate sum of iterating each one of these methods 250 million times. Assuming that it would take 100ms for a human to perceive delay and that the worst/better difference is 2.58 millis it would imply that you would need almost a trillion (1000 * 1000 millions) iterations to perceive the difference between different methods.
Summing it up: use if-else it's one of those cases where the fastest option is also the one with more legibility and less error-prone.
// methods used to measure difference between if and if/else
/** equality is not important **/
private static int comparatorOfIfElse(int a, int b) {
if(a < b) return -1;
else return 1;
}
/** equality is taken into account using if/else **/
private static int comparatorOfIfElseIf(int a, int b) {
if(a < b) return -1;
else if(a > b) return 1;
return 0;
}
/** equality is taken into account using only if **/
private static int comparatorOfIf(int a, int b) {
if(a < b) return -1;
if(a > b) return 1;
return 0;
}
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
The fastest would be a table dispatch, which is what a switch statement gets optimized into when there are enough cases in it (if there are few cases in a switch, it gets translated into a series of if-else checks in the resulting machine code).
The decision to use many if-statements or one if-elseif-elseif... should not rely on performance, since this decision involves the program flow massively.
I doubt that you can switch from many if-statements to a big if-elseif without loosing functionality.
Its a design question, not a perfomance one.

if statement condition optimisation

I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.
if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?
if ( (condition1) | (condition2) ){
// do this
}
or would I need to nest two if statements to only check the second condition if the first evaluates to false?
if (condition1){
// do this
}else if (condition2){
// do this
}
I am working in PHP, however, I assume that this may be language-agnostic.
For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.
An old trick for doing obfuscated code was to use this to create if statements, such as:
a || b();
if "a" is true, "b()" would never be evaluated, so we can rewrite it into:
if(!a)
b();
and similarly:
a && b();
would become
if(a)
b();
Please note that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".
EDIT:
As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.
First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.
Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.
Pretty much every language does a short circuit evaluation. Meaning the second condition is only evaluated if it's aboslutely necessary to. For this to work, most languages use the double pipe, ||, not the single one, |.
See http://en.wikipedia.org/wiki/Short-circuit_evaluation
In C, C++ and Java, the statement:
if (condition1 | condition2) {
...
}
will evaluate both conditions every time and only be true if the entire expression is true.
The statement:
if (condition1 || condition2) {
...
}
will evaluate condition2 only if condition1 is false. The difference is significant if condition2 is a function or another expression with a side-effect.
There is, however, no difference between the || case and the if/else case.
I've seen a lot of these types of questions lately--optimization to the nth degree.
I think it makes sense in certain circumstances:
Computing condition 2 is not a constant time operation
You are asking strictly for educational purposes--you want to know how the language works, not to save 3us.
In other cases, worrying about the "fastest" way to iterate or check a conditional is silly. Instead of writing tests which require millions of trials to see any recordable (but insignificant) difference, focus on clarity.
When someone else (could be you!) picks up this code in a month or a year, what's going to be most important is clarity.
In this case, your first example is shorter, clearer and doesn't require you to repeat yourself.
According to this article PHP does short circuit evaluation, which means that if the first condition is met the second is not even evaluated.
It's quite easy to test also (from the article):
<?php
/* ch06ex07 – shows no output because of short circuit evaluation */
if (true || $intVal = 5) // short circuits after true
{
echo $intVal; // will be empty because the assignment never took place
}
?>
The short-circuiting is not for optimization. It's main purpose is to avoid calling code that will not work, yet result in a readable test. Example:
if (i < array.size() && array[i]==foo) ...
Note that array[i] may very well get an access violation if i is out of range and crash the program. Thus this program is certainly depending on short-circuiting the evaluation!
I believe this is the reason for writing expressions this way far more often than optimization concerns.
While using short-circuiting for the purposes of optimization is often overkill, there are certainly other compelling reasons to use it. One such example (in C++) is the following:
if( pObj != NULL && *pObj == "username" ) {
// Do something...
}
Here, short-circuiting is being relied upon to ensure that pObj has been allocated prior to dereferencing it. This is far more concise than having nested if statements.
Since this is tagged language agnostic I'll chime in. For Perl at least, the first option is sufficient, I'm not familiar with PHP. It evaluates left to right and drops out as soon as the condition is met.
In most languages with decent optimization the former will work just fine.
The | is a bitwise operator in PHP. It does not mean $a OR $b, exactly. You'll want to use the double-pipe. And yes, as mentioned, PHP does short-circuit evaluation. In similar fashion, if the first condition of an && clause evaluates to false, PHP does not evaluate the rest of the clause, either.
VB.net has two wonderful expression called "OrElse" and "AndAlso"
OrElse will short circuit itself the first time it reaches a True evaluation and execute the code you desire.
If FirstName = "Luke" OrElse FirstName = "Darth" Then
Console.Writeline "Greetings Exalted One!"
End If
AndAlso will short circuit itself the first time it a False evaluation and not evaluate the code within the block.
If FirstName = "Luke" AndAlso LastName = "Skywalker" Then
Console.Writeline "You are the one and only."
End If
I find both of these helpful.

Categories