• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Crusable77

Switch vs if else

20 posts in this topic

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

Share this post


Link to post
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.
2

Share this post


Link to post
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.
2

Share this post


Link to post
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.
2

Share this post


Link to post
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 [url="http://en.wikipedia.org/wiki/Branch_table"]jump/branch table[/url]. Additonally, in some languages, you are allowed to [i]fall through[/i] a case statement.
[code]
switch (x) {
case 0:
doSomething();
case 1:
doSomethingElse();
break;
default:
doDefault();
break;
}
[/code]

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

Share this post


Link to post
Share on other sites
[quote name='alnite' timestamp='1352658607' post='4999971']
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 [url="http://en.wikipedia.org/wiki/Branch_table"]jump/branch table[/url]. Additonally, in some languages, you are allowed to [i]fall through[/i] a case statement.
[code]
switch (x) {
case 0:
doSomething();
case 1:
doSomethingElse();
break;
default:
doDefault();
break;
}
[/code]

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

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

Share this post


Link to post
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.
0

Share this post


Link to post
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 [url="http://en.wikipedia.org/wiki/Trie"]trie[/url], which is even faster in some cases. I've only ever needed to do this once in 30 years of programming experience.
1

Share this post


Link to post
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!
0

Share this post


Link to post
Share on other sites
[quote name='Álvaro' timestamp='1352665257' post='4999999']
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 [url="http://en.wikipedia.org/wiki/Trie"]trie[/url], which is even faster in some cases. I've only ever needed to do this once in 30 years of programming experience.
[/quote]
That link made no sense to me, am I worthy of the title programmer [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]?

In all seriousness, it's a matter of preference. What I generally do is if I have something where I'm saying:
[CODE]
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;
}
}
}
[/CODE]
I'll use if-else statements (The code above is unformatted and terrible, forgive me [img]http://public.gamedev.net//public/style_emoticons/default/unsure.png[/img]!).
But, If I have something where it's not nested and it's just a series of:
[CODE]
if ()
{
}
else if ()
{
}
else if ()
{
}
[/CODE]
I'd use a switch statement because it'd probably be easier to read and understand.
0

Share this post


Link to post
Share on other sites
[quote name='Mathew Bergen' timestamp='1352596183' post='4999781']
Hello, Is there any difference between using a switch statement and maybe 5 if else statements? By difference i mean performance wise,
[/quote]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.
0

Share this post


Link to post
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.
0

Share this post


Link to post
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.
[/quote]

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
0

Share this post


Link to post
Share on other sites
[quote name='Álvaro' timestamp='1352744129' post='5000289']
[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.
[/quote]

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

Share this post


Link to post
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):
[CODE] 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;
}[/CODE]
This would be both faster and easier to maintain:
[CODE] const static int iTable[] = {
4,
5,
6,
7,
};
int iLocal = iTable[argc];[/CODE]

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
2

Share this post


Link to post
Share on other sites
[quote name='Álvaro' timestamp='1352744129' post='5000289']
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]

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 [b]not[/b] want to touch your factory (or event dispatcher) every single time a new class/message is added.
1

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1352768305' post='5000400']
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.”[/quote]That's not entirely true.

In practice a compiler [i]might[/i] 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.
1

Share this post


Link to post
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
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0