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;
} 
dalloliogm
  • 8,718
  • 6
  • 45
  • 55
Ballu Rocks
  • 1,206
  • 3
  • 13
  • 15
  • 35
    Premature optimization - neither option is going to save any noticeable amount of time. Go with whatever's more readable to you. – DCoder May 27 '12 at 09:53
  • 3
    Due to the fact that "switch" does no comparison, it is slightly faster. – Marduk May 27 '12 at 09:54
  • 2
    @Marduk how can switch do no comparison? – will May 27 '12 at 09:57
  • 2
    @Marduk: How do you think `x` and `1` are compared? Exactly, internally it also performs a `==` comparison. – ThiefMaster May 27 '12 at 09:57
  • 1
    don't go deep into the code sir.. i am not asking the logic.. i asked which is better method..if ...or switch.. – Ballu Rocks May 27 '12 at 10:02
  • @BalluRocks, See http://stackoverflow.com/q/7290889/632951 – Pacerier Mar 05 '15 at 19:54
  • 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. – Ajowi Jul 13 '22 at 09:05
  • Performance is second to readability. In 99% of all cases where I've seen else-if switch would be better – Rid Iculous Aug 23 '22 at 00:08
  • 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`. – squarecandy Feb 01 '23 at 14:20

9 Answers9

166

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.

samayo
  • 16,163
  • 12
  • 91
  • 106
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 4
    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. – jortsc Sep 12 '13 at 16:07
  • 5
    There is actually a way for complex switch case: = 0: ...; break; } – SenseException May 12 '14 at 09:48
  • 1
    `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). ` – A Friend Dec 11 '19 at 06:01
  • @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. – Andrew Dinmore Dec 11 '19 at 09:39
  • @AndrewDinmore Not from what I've seen. Just ran some code about 20 times, `else if` was faster every time. See for youself: http://sandbox.onlinephpfunctions.com/code/ac23bdfc14526209c12633e6b7e15b2e6cb056d7 – A Friend Dec 11 '19 at 14:53
  • 1
    @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. – Andrew Dinmore Dec 12 '19 at 14:29
  • @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. – A Friend Dec 12 '19 at 16:52
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.

Hurricane Development
  • 2,449
  • 1
  • 19
  • 40
Guest
  • 361
  • 3
  • 2
  • 4
    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. – Hurricane Development Dec 18 '16 at 02:42
  • 1
    Add sources whenever possible and - better yet - add a link to and a quote from the documentation. – Jon Doe Dec 18 '16 at 02:52
  • CRAP index aka Cyclometric Complexity index proof otherwise. NPATH is shorter for switch. – Digital Human May 25 '22 at 10:19
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...

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 3
    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! – darkheir Aug 30 '13 at 13:01
  • for small number of comparisons, yes. but as darkheir mentioned, its not true for other cases. – pcarvalho Nov 04 '14 at 13:29
  • 4
    *"*General rule is to use...."* [**[citation needed]**](http://en.wikipedia.org/wiki/Weasel_word). Also see http://stackoverflow.com/q/7290889/632951 – Pacerier Mar 05 '15 at 19:55
  • 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 block – user889030 Apr 13 '22 at 06:28
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 ===.

Dan Bray
  • 7,242
  • 3
  • 52
  • 70
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.

sczdavos
  • 2,035
  • 11
  • 37
  • 71
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

AdM
  • 21
  • 1
1

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)

JanBal
  • 39
  • 7
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.

will
  • 10,260
  • 6
  • 46
  • 69
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