Which is Faster and better, Switch Case or if else if?
Asked Answered
S

10

83

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;
} 
Snob answered 27/5, 2012 at 9:51 Comment(9)
Premature optimization - neither option is going to save any noticeable amount of time. Go with whatever's more readable to you.Tiresome
Due to the fact that "switch" does no comparison, it is slightly faster.Coburg
@Coburg how can switch do no comparison?Adipocere
@Marduk: How do you think x and 1 are compared? Exactly, internally it also performs a == comparison.Doehne
don't go deep into the code sir.. i am not asking the logic.. i asked which is better method..if ...or switch..Snob
@BalluRocks, See https://mcmap.net/q/244020/-what-is-the-difference-between-switch-case-and-if-else-in-php/632951Flop
Where the ifs are becoming many, personally I think switch should be used. As for performance, I have no idea on this but from other answers, the difference seems negligible.Cromwell
Performance is second to readability. In 99% of all cases where I've seen else-if switch would be betterPolychasium
Personally I find the indentation code style of switch and having to call break; at the end of each section harder to deal with than even a long string of elseif.Prognathous
D
170

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.

Doehne answered 27/5, 2012 at 9:53 Comment(7)
You've said that use if elseif or switch is mainly a matter of preference, and that the performance is the same. I disagree with you, the switch sentence is evaluated once and then the result is compared with each case, and if elseif is evaluated again and again. For this I think that depending where and how the condition is, one or another will be more faster and appropiated.Fluorescein
There is actually a way for complex switch case: <?php $i = // an int switch(true) { case $i < 0: ...; break; case $i >= 0: ...; break; }Seasickness
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
@AFriend Though (at last I checked) the performance is slightly better with the single word elseif as the interpreter only has to process a one instruction, rather than two.Yates
@AndrewDinmore Not from what I've seen. Just ran some code about 20 times, else if was faster every time. See for youself: sandbox.onlinephpfunctions.com/code/…Daffie
@AFriend I'm seeing it flip between the two as to which of your sets is faster. The difference between one and the other will be extremely small though; other things running on the server and processor cache for your other operations is probably going to affect that test as much if not more. Once it's in the opcache, there may be no difference at all, but on first pass the separate words must be slower as they'll be treated as separate tokens. Still, the difference is insignificant to the point of being irrelevant in the real world and only mentioned for interest's sake.Yates
@AndrewDinmore yes, some good points there. And yes, I 100% agree, the speed difference is never really going to affect most real world applications but it's some good food for thought.Daffie
T
36

According to phpbench.com, if/elseif is slightly faster, especially when using strict comparison (===).

enter image description here

But it'll only really matter if you want to shave off microseconds on a function that'll be called thousands of times.

Termite answered 18/12, 2016 at 2:20 Comment(3)
This is a good contribution to the answer, but you need to add more information for it to be a useful answer. At the very least link to the part of 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
Add sources whenever possible and - better yet - add a link to and a quote from the documentation.Bruce
CRAP index aka Cyclometric Complexity index proof otherwise. NPATH is shorter for switch.Apologia
S
21

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...

Studdard answered 27/5, 2012 at 10:51 Comment(4)
Hum in your benchmark the 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
for small number of comparisons, yes. but as darkheir mentioned, its not true for other cases.Scholar
"*General rule is to use...." [[citation needed]](en.wikipedia.org/wiki/Weasel_word). Also see https://mcmap.net/q/244020/-what-is-the-difference-between-switch-case-and-if-else-in-php/632951Flop
hmmmm i find 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 blockAmmonic
J
4

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 ===.

Johnnajohnnie answered 13/5, 2017 at 14:27 Comment(0)
T
2

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.

Turbojet answered 27/5, 2012 at 9:55 Comment(0)
P
2

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)

Patty answered 25/6, 2020 at 9:29 Comment(0)
C
2

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

Corporal answered 23/5, 2021 at 1:2 Comment(0)
A
0

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.

Adipocere answered 27/5, 2012 at 9:55 Comment(0)
O
0

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

Orchestra answered 27/5, 2012 at 10:2 Comment(1)
Opinions are good if they are backed with data and facts.Flop
B
0

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.

https://derickrethans.nl/php7.2-switch.html

Berkley answered 31/5 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.