#1 Members - Reputation: 341
Posted 10 November 2012 - 07:09 PM
"C spilled his beer all over C++'s shirt. Outraged, C++ shouted, "Good god, man! Have you no class?"
"Your mother is so fat that the recursive function that was used to calculate her mass created a stack overflow"
#2 Members - Reputation: 3789
Posted 10 November 2012 - 07:20 PM
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 Members - Reputation: 341
Posted 10 November 2012 - 07:39 PM
"C spilled his beer all over C++'s shirt. Outraged, C++ shouted, "Good god, man! Have you no class?"
"Your mother is so fat that the recursive function that was used to calculate her mass created a stack overflow"
#4 Members - Reputation: 3789
Posted 10 November 2012 - 08:01 PM
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 GDNet+ - Reputation: 1547
Posted 11 November 2012 - 01:18 AM
OpenChess - 1.0 done!
Classic RPG #1 - Task 9 -> January 1st 2013
#6 Members - Reputation: 1173
Posted 11 November 2012 - 03:49 AM
So, in short, prefer switch/case over else/ifs.
#7 Members - Reputation: 1396
Posted 11 November 2012 - 12:30 PM
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 Members - Reputation: 380
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 Members - Reputation: 1050
Posted 11 November 2012 - 01:22 PM
#10 Members - Reputation: 5795
Posted 11 November 2012 - 02:20 PM
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.
#12 Crossbones+ - Reputation: 1372
Posted 11 November 2012 - 07:03 PM
That link made no sense to me, am I worthy of the title programmerThis 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.
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.
Here's Breakout:
Breakout!
If you need some photo editing done, contact me:
superman3275@gmail.com
if you want some programming help, or are recruiting for a game development team, either PM me on here or email me up there
#14 Members - Reputation: 1949
Posted 12 November 2012 - 01:29 AM
Given only those choices, the switch is preferable for readability, but performance-wise there isn't much in it.Hello, Is there any difference between using a switch statement and maybe 5 if else statements? By difference i mean performance wise,
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.
My website dedicated to sorting algorithms
#15 Moderators - Reputation: 3281
Posted 12 November 2012 - 11:59 AM
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.
#16 Members - Reputation: 5795
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 Members - Reputation: 3283
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 Crossbones+ - Reputation: 5143
Posted 12 November 2012 - 06:58 PM
#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.
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
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums
#19 Members - Reputation: 1297
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.
#20 Members - Reputation: 1949
Posted 13 November 2012 - 12:03 AM
That's not entirely true.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.”
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.
My website dedicated to sorting algorithms






