Switch vs if else

Started by
19 comments, last by L. Spiro 11 years, 6 months ago
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!
Advertisement

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 tongue.png?

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 unsure.png!).
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.

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

Don't forget logical operators. A few ANDs && could get rid of various if in there.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator


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.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
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.
enum Bool { True, False, FileNotFound };

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

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid


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.
f@dzhttp://festini.device-zero.de

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.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement