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;
}
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.
In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word).
–
Daffie elseif
as the interpreter only has to process a one instruction, rather than two. –
Yates else if
was faster every time. See for youself: sandbox.onlinephpfunctions.com/code/… –
Daffie 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.
phpbench.com
and directly quote the important parts in this answer. I will edit your post to show you what a well formated answer looks like. –
Onofredo 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...
switch
and if/else
are performed on only two options. i know in C#
for example switch
will use a lookup table and is faster begining at 5 choices. I've performed the same performance test as your benchmark but with 10 choices instead of 2 and switch
appears to be faster! –
Geotaxis if / else if
easy to read compare to switch statements because they if braces can take u quickly between code blocks while in switch case good luck with finding break statement on your own , while in if case even notepad trace the braces and give option to minimize code block –
Ammonic 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
Note that PHP 7.2 includes a feature where switch statements are converted to branch tables if all the case conditions are integers, or all are strings.
This means that switch statements with many simple cases (for example 1,2,3,4,5,6...) are much more efficient because it selects the nth entry in the list rather than having to compare every condition. I imagine it works best with dense lists rather than sparse ones (like 4,75,350) but seems to be a welcome advance in performance.
This is of course the way that an assembly programmer would pick up a number and turn it into a specific action, or error message for example.
For it to detect this and work, every case has to be an integer, or every case has to be a string. Once you add mixed things into the list of cases, it's no longer possible to build a branch table.
© 2022 - 2024 — McMap. All rights reserved.
x
and1
are compared? Exactly, internally it also performs a==
comparison. – Doehneswitch
and having to callbreak;
at the end of each section harder to deal with than even a long string ofelseif
. – Prognathous