Jump to content

  • Log In with Google      Sign In   
  • Create Account

Switch vs if else


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
20 replies to this topic

#1 Crusable   Members   -  Reputation: 594

Like
0Likes
Like

Posted 10 November 2012 - 07:09 PM

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

Sponsor:

#2 mhagain   Crossbones+   -  Reputation: 7970

Like
0Likes
Like

Posted 10 November 2012 - 07:20 PM

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

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#3 Crusable   Members   -  Reputation: 594

Like
0Likes
Like

Posted 10 November 2012 - 07:39 PM

so it is just preference wise?

#4 mhagain   Crossbones+   -  Reputation: 7970

Like
2Likes
Like

Posted 10 November 2012 - 08:01 PM

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.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#5 Black-Rook   Members   -  Reputation: 1563

Like
2Likes
Like

Posted 11 November 2012 - 01:18 AM

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.
GameDev Journal: http://www.gamedev.n...-rooks-journal/

OpenChess - 1.0 done!

Classic RPG #1 - Task 9 -> January 1st 2013

#6 Rattenhirn   Crossbones+   -  Reputation: 1751

Like
2Likes
Like

Posted 11 November 2012 - 03:49 AM

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.


#7 alnite   Crossbones+   -  Reputation: 2107

Like
1Likes
Like

Posted 11 November 2012 - 12:30 PM

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, 11 November 2012 - 12:30 PM.


#8 !Null   Members   -  Reputation: 380

Like
0Likes
Like

Posted 11 November 2012 - 01:19 PM

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
/********************************************************************************\
/**********************He Who Dares, Wins**********************************\
/********************************************************************************\

#9 6677   Members   -  Reputation: 1058

Like
0Likes
Like

Posted 11 November 2012 - 01:22 PM

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.

#10 Álvaro   Crossbones+   -  Reputation: 13311

Like
1Likes
Like

Posted 11 November 2012 - 02:20 PM

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.

#11 Rattenhirn   Crossbones+   -  Reputation: 1751

Like
0Likes
Like

Posted 11 November 2012 - 02:38 PM

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!

#12 superman3275   Crossbones+   -  Reputation: 2011

Like
0Likes
Like

Posted 11 November 2012 - 07:03 PM

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 Posted Image?

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 Posted Image!).
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 ph34r.png!

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 smile.png!


#13 TheChubu   Crossbones+   -  Reputation: 4349

Like
0Likes
Like

Posted 11 November 2012 - 07:13 PM

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


#14 iMalc   Crossbones+   -  Reputation: 2306

Like
0Likes
Like

Posted 12 November 2012 - 01:29 AM

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

#15 hplus0603   Moderators   -  Reputation: 5303

Like
0Likes
Like

Posted 12 November 2012 - 11:59 AM

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 };

#16 Álvaro   Crossbones+   -  Reputation: 13311

Like
0Likes
Like

Posted 12 November 2012 - 12:15 PM

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, 12 November 2012 - 12:17 PM.


#17 Serapth   Crossbones+   -  Reputation: 5465

Like
0Likes
Like

Posted 12 November 2012 - 12:29 PM


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?


Hashtable of creator functions.

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

#18 L. Spiro   Crossbones+   -  Reputation: 13581

Like
2Likes
Like

Posted 12 November 2012 - 06:58 PM

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, 13 November 2012 - 02:04 PM.

It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#19 Trienco   Crossbones+   -  Reputation: 2172

Like
1Likes
Like

Posted 12 November 2012 - 10:59 PM

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

#20 iMalc   Crossbones+   -  Reputation: 2306

Like
1Likes
Like

Posted 13 November 2012 - 12:03 AM

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




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS