# Switch vs if else

This topic is 1897 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, Is there any difference between using a switch statement and maybe 5 if else statements? By difference i mean performance wise,

##### Share on other sites
Your compiler is highly likely to generate the exact same code for both, but it is dependent on your compiler.

##### Share on other sites
so it is just preference wise?

##### Share on other sites
Use whichever gives you the cleanest code.

This is honestly a micro-optimization in 99% of cases, and any performance-related preference for one over the other should be backed up by profiling. See http://stackoverflow.com/questions/2086529/what-is-the-relative-performance-difference-of-if-else-versus-switch-statement-i for further discussion, Java-specific but much of it is generally applicable.

##### Share on other sites
I will use a switch statement if I'm dealing with a lot of checks. If it's just a few, "else if" will be good enough. They will all accomplish the same thing, code wise.

##### Share on other sites
All other things being equal, switch expresses your intent more clearly. While it may not matter to the compiler, it will matter to readers of your code including your future self. Having a bunch of else ifs will force them to examine the whole construct in detail to hunt down the reason, why it is not a simple switch/case.

So, in short, prefer switch/case over else/ifs.

##### Share on other sites
While this might be language-dependent, you can't normally switch-case objects like strings. switch-case could only be used on integers, as it creates a jump/branch table. Additonally, in some languages, you are allowed to fall through a case statement.
 switch (x) { case 0: doSomething(); case 1: doSomethingElse(); break; default: doDefault(); break; } 

if x = 0, doSomething() and doSomethingElse() are executed. This style of coding could be useful in certain cases (no pun intended). Edited by alnite

##### Share on other sites

While this might be language-dependent, you can't normally switch-case objects like strings. switch-case could only be used on integers, as it creates a jump/branch table. Additonally, in some languages, you are allowed to fall through a case statement.
 switch (x) { case 0: doSomething(); case 1: doSomethingElse(); break; default: doDefault(); break; } 

if x = 0, doSomething() and doSomethingElse() are executed. This style of coding could be useful in certain cases (no pun intended).

You are right. This is a language dependent thing because i know that in java 1.7 switch statements support strings

##### Share on other sites
C# switches support quite a few datatypes. String and char being 2 examples. Any datatype usually represented as a class though does not work such as XNA's gamepad state object. C# also does not allow fall throughs so although the basic principle is the same there are language dependant alterations.

##### Share on other sites
This thread is about using switch in C++. You can only use switch on an integer type, and it is particularly common to use it on an enum.

If you need to use a switch with a string and performance is critical, convert the string to an enum and then switch on the enum. This conversion can be done easily with a hash (unordered_map, in C++11 speak) or you can implement a trie, which is even faster in some cases. I've only ever needed to do this once in 30 years of programming experience.

##### Share on other sites
When using enums switch/case has one more advantage:
Many compilers will warn you if you forget to add values of the enum to the possible cases. This can be very valuable!

##### Share on other sites

This thread is about using switch in C++. You can only use switch on an integer type, and it is particularly common to use it on an enum.

If you need to use a switch with a string and performance is critical, convert the string to an enum and then switch on the enum. This conversion can be done easily with a hash (unordered_map, in C++11 speak) or you can implement a trie, which is even faster in some cases. I've only ever needed to do this once in 30 years of programming experience.

That link made no sense to me, am I worthy of the title programmer ?

In all seriousness, it's a matter of preference. What I generally do is if I have something where I'm saying:
 if (x == true) { if (y == false) { if (z = 1) { std::cout << "Z = 1!" << std::endl; } else if (z == 2) { std::cout << "Z = 2" << std::endl; } } } 
I'll use if-else statements (The code above is unformatted and terrible, forgive me !).
But, If I have something where it's not nested and it's just a series of:
 if () { } else if () { } else if () { } 
I'd use a switch statement because it'd probably be easier to read and understand.

##### Share on other sites
Don't forget logical operators. A few ANDs && could get rid of various if in there.

##### Share on other sites

Hello, Is there any difference between using a switch statement and maybe 5 if else statements? By difference i mean performance wise,
Given only those choices, the switch is preferable for readability, but performance-wise there isn't much in it.

If performance is what you are after, then you should really be broadening your choices. The whole thing can often be replaced with:
One virtual function call, or
One table loopkup, or
A clever calculation.

These things require much more context of what is going on. With the superficial example that you gave, there really isn't any scope for real optimisation to take place.

##### Share on other sites
Using switch, and using if/else, are both signs that your code doesn't quite match your data.

If your code matches your data perfectly, there will only be virtual dispatch -- you'll get the right behavior by calling the right virtual method on the right object instance.
In practice, you can't always achieve this, especially when data validation is concerned, but you can get pretty close in most business logic, and it's often worth it to take a long look at the data you're working with, and figuring out how you can map code behavior to data without using if/else or switch.

##### Share on other sites

Using switch, and using if/else, are both signs that your code doesn't quite match your data.

That's a bit too general, don't you think? Without using switch or a bunch if-else statements, what does an event dispatcher look like? How do you implement a factory function? Edited by Álvaro

##### Share on other sites

[quote name='hplus0603' timestamp='1352743150' post='5000283']
Using switch, and using if/else, are both signs that your code doesn't quite match your data.

That's a bit too general, don't you think? Without using switch or a bunch if-else statements, what does an event dispatcher look like? How do you implement a factory function?
[/quote]

Hashtable of creator functions.

Although I agree with you, that advice is a bit... extreme. Especially given this is the beginners forum.

##### Share on other sites
I disagree with anyone who says either of the following:
#1: The performance is about the same.
#2: The compiler will usually generate the same code.

For #2, there is no rule that says what a compiler should do, but there are common practices that are extremely consistent between all compilers I have ever used, and as the author of MHS (Memory Hacking Software) I have done a lot of snooping around code that was compiled by compilers I have never used, still finding the exact same patterns being used.

Those patterns are explained here: http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/
Again, no rule in the language forces this type of output, but as an unspoken rule among compilers, when possible they will all generate jump tables in order to gain in performance.
So it can’t be stated that the compiler will usually generate the same code. Just sometimes, and only if you don’t allow it to do otherwise.

Since the whole purpose of a jump table is to increase performance, #1 is also incorrect. The performance is only sometimes the same, again only if the compiler has no choice.
More accurately, “A switch case is never slower than an if-else-else-else, but sometimes (always, if you know what you are doing) faster.”
I have restricted the scope of that statement to cases in which the end result will be the same either route, since there are cases in which switch() simply can’t do the same thing as if-else-else-else, but it is assumed by the topic starter that we are only considering cases where equivalent results are possible.

All of that being said, both if-else-else-else and switch cases are often abused.
You really should only be using them if the logic changes for each case, or when the case numbers themselves are too spread apart to be able to represent with a data table or 2.
In other words, this is an abuse of a switch case (taken from that link):
 int iLocal = 0; switch( argc ) { case 0: iLocal = 4; break; case 1: iLocal = 5; break; case 2: iLocal = 6; break; case 3: iLocal = 7; break; }
This would be both faster and easier to maintain:
 const static int iTable[] = { 4, 5, 6, 7, }; int iLocal = iTable[argc];

Data tables are always clearer, more concise, faster, and easier to maintain/upgrade/expand in the future. They also take up less screen space, which is valuable.
You should always use them when possible.
Save switch cases for changes in logic that can’t be expressed easily by data tables or other means.

L. Spiro Edited by L. Spiro

##### Share on other sites

That's a bit too general, don't you think? Without using switch or a bunch if-else statements, what does an event dispatcher look like? How do you implement a factory function?

Event dispatchers can use runtime type information or simply strings and just forward events to all handlers that registered themselves for certain message types. I'd actually be a bit sceptical if my event dispatcher starts switch/casing over event types. Same for a factory. A factory using a big switch/case is usually considered the "naive" approach and while typically good enough, it's probably the least desirable implementation. Generally you do not want to touch your factory (or event dispatcher) every single time a new class/message is added.

##### Share on other sites

More accurately, “A switch case is never slower than an if-else-else-else, but sometimes (always, if you know what you are doing) faster.”
That's not entirely true.

In practice a compiler might produce a binary decision tree of tests to find the right case, resulting in about 2-3 tests each time.
Whereas an if-else chain can be structued such that the more frequent cases are explicitly tested for first. If the first case accounts for 95% of the time, then it will be a net win over a binary decision tree that the compiler may generate.
I'm not saying compilers do this frequently, it's merely that they can do. Profile guilded optimisers can probably make the decision better.

Besides, the main reason for saying that performance is about the same is that we're only taking about a specific case of 5 cases here. Unless the code for each one is really basic, then that should be negligible in the grand scheme of things.

##### Share on other sites
Actually what you said is correct, and for me to use the word “never” is a bit too strong.
So I am going to openly take fault on saying it that way, using the word “never” inappropriately. It is a common quote that “--I” is never slow than, and sometimes faster than “I++”, and I derived my own quote from there.
But the overall message I feel is the same specifically because of what is in the parentheses. You can order the switch cases as easily as you can order if-else-else-else, and as of yet I haven’t seen compilers emitting any code that re-orders these, and that makes sense since the compiler can’t possibly predict what the human sees as the most common cases.
So ultimately the switch case’s order is no worse than the same person using an if-else-else, since that same person would not have changed the order for the switch case. Inside my parentheses, we assume an expert-level person is coding, but in the end as long as the logic between both the switch case and the if-else-else is the same and the coder, being an expert, tried to take advantage of each of their strengths, the output for the switch case would be the same as that of the if-else-else.

Once again I point out that the standard does not enforce this; this is just what I have observed over many compilers in person and not in-person during hacking. Every compiler that seems to be under the sun seems to work the same way on switch cases so it is easier just encompass that with the word “always”. It is basically a well understood algorithm for switch cases and is universally implemented across compilers because doing otherwise would leave that compiler at a disadvantage. I see no variations when looking at disassembly between any of the major compilers today that suggests any reason to compile to anything else, which suggests that it is both a well understood and fully solved problem that all compilers will implement.

Basically, the key point is within the parentheses, because anyone how knows how they both work as far as any compiler that actually is in use today works, they should be able to engineer a switch case that is never slower than an if-else-else-etc.
But the most key point is actually below that diatribe. Simply by not abusing switch cases or if-else-else you can gain both a performance increase and clearer and smaller code.

L. Spiro