Original Post
Hello, Is there any difference between using a switch statement and maybe 5 if else statements? By difference i mean performance wise,
switch (x) {
case 0:
doSomething();
case 1:
doSomethingElse();
break;
default:
doDefault();
break;
}
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).
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.
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;
}
}
}
if ()
{
}
else if ()
{
}
else if ()
{
}
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,
Using switch, and using if/else, are both signs that your code doesn't quite match your data.
[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.
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;
} const static int iTable[] = {
4,
5,
6,
7,
};
int iLocal = iTable[argc];
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?
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.”
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more