473,396 Members | 1,809 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Switch vs. Else If

Simple question. I am optimizing some C++ code and I'd like to know which
is faster (or if there is any difference at all) between using a switch
statement or nested else-ifs. I'm partial to else-if. I know to put the if
statement that is most likely to be true at the top of the else-if chain -so
as to minimize checks. I've searched around online and mainly found answers
to this question for Java programmers.

Thanks in advance,
Michael
Dec 20 '05 #1
13 7519
Michael Griebe wrote:
Simple question. I am optimizing some C++ code
Ah, so you...

- refactored the code to make it beautiful and clean
- wrote lots of unit tests so it's safe to change
- and used a profiler to measure its speed

?

If so, you would inspect the profiler output (maybe across a rigged test
case that calls a target function a zillion times). Then you would make a
small tweak, run again, and see how the code changed.
and I'd like to know which
is faster (or if there is any difference at all) between using a switch
statement or nested else-ifs.
There's no way to guess.
I'm partial to else-if.
Both else-if and switch are a "chain of conditionals".

Sometimes a chain of conditionals should be refactored into polymorphism. So
the third alternative, which I am partial to, is virtual methods.

However, you can't know which will always be faster. A compiler might
optimize one else-if chain into the same opcodes as a simple switch
statement. And it might pessimize a given switch statement into the opcodes
for an else-if chain.

Then, one set of opcodes might overflow your CPU cache, where another did
not, so the performance would change again.

Similarily, virtual methods might be faster or slower.

The only way to optimize is to profile and find the slow parts. Then spend
time speeding them up. Only 20% of your code will have an 80% effect on
performance, and if you optimize the wrong part of the code then you only
waste time and increase risk.
I've searched around online and mainly found answers
to this question for Java programmers.


That's because there's only one Java implementation, and only one Java
Virtual Machine, so there's a simpler answer.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Dec 20 '05 #2
Michael Griebe wrote:
Simple question. I am optimizing some C++ code and I'd like to know which
is faster (or if there is any difference at all) between using a switch
statement or nested else-ifs. I'm partial to else-if. I know to put the if
statement that is most likely to be true at the top of the else-if chain -so
as to minimize checks. I've searched around online and mainly found answers
to this question for Java programmers.


Short answer: It's an implementation detail. There is nothing in the
C++ Standard that requires a compiler to generate better or worse code
for a switch statement vs nested if-else statements.

Longer - and arguably more relevant - answer: switch statements may
make it easier for a compiler to generate faster code. Depending on
several factors, the compiler may be able to generate a lookup table of
goto's based on the switch value. There is no requirement that the
compiler do so - indeed, there is no reason why a shrewd compiler
couldn't generate a lookup table out of nested if-else's - but it is a
relatively simple optimization for a compiler writer to implement. A
look-up table has constant time lookup, regardless of the value of the
switch value, whereas nested if-else statement would typically require
linear lookup time (which would typically take longer).

g++ implements look-up tables for appropriate switch statements. I
would hazard a guess that several other compilers do so as well, but I
haven't checked.

So, if your goal is to generate efficient code, a switch statement may
offer some advantages. It's also more clearly shows the programmer's
intent, in my opinion - which obviously differs from your opinion.

Best regards,

Tom

Dec 20 '05 #3
I think pointers to functions are the fastest .
for example ...

#include <iostream.h>
void choice1() , choice2() , choice3();

void (*do_choice [3]() = {choice1,choice2,choice3};

int main (void)
{
char ch;

cout << "make your choice : ";
cin >> ch;
cin.get();
ch -= '1 '; // arry starts on 0 , -1 for the right beginning
if (ch<0 || ch>2) cout << endl << "choice doesent exist !";
else do_choice[ch]();
return 0;
}

void choice1(void) { ...... }
void choice2(void) { ...... }
void choice3(void) { ...... }

you can also put your functon inline ,
this will take up memoryspace but it will make your program run faster
..
you can never use an inline function in a loop .
This is not a good answer to your question but i hope you like my
alternative .

Greets.

Dec 20 '05 #4
Please quote some context from the message you are replying to.

vo******@gmail.com wrote:
I think pointers to functions are the fastest .
You think? Why do you think that? Unless you have profiled the code and
proved that this is a bottleneck and using function pointers speeds
things up then what you think is irrelevant.
for example ...

#include <iostream.h>
That's not a C++ header, it's an old pre-standard header. You want
<iostream>. You will need to qualify all the standard library names
with std::
void choice1() , choice2() , choice3();

void (*do_choice [3]() = {choice1,choice2,choice3};
You missed a closing parenthesis there. Should be

void (*do_choice [3])() = {choice1,choice2,choice3};
int main (void)
The void is not necessary here and so is not common C++ style. int
main()
{
char ch;
What is wrong with int?
cout << "make your choice : ";
cin >> ch;
cin.get();
ch -= '1 '; // arry starts on 0 , -1 for the right beginning
if (ch<0 || ch>2) cout << endl << "choice doesent exist !";
Are you particularly keen to flush the buffer? There's nothing wrong
with

if (ch<0 || ch>2) std::cout << "\nchoice doesent exist !";
else do_choice[ch]();
return 0;
}

void choice1(void) { ...... }
void choice2(void) { ...... }
void choice3(void) { ...... }


Gavin Deane

Dec 20 '05 #5
On 2005-12-20, Michael Griebe <mi***********@hotmail.com> wrote:
Simple question. I am optimizing some C++ code and I'd like to
know which is faster (or if there is any difference at all)
between using a switch statement or nested else-ifs. I'm
partial to else-if.


They are not semantically equivalent. Most else-if constructs
will not be convertible to a switch statement. Due to
fall-through and break, many switch constructs will not be
convertible to else-if.

So it seems like a waste of time to optimize in this way. Both a
switch and an else-if can be optimized to put most frequent cases
near the top, so do *that* intead, based on profiling, and don't
worry about, er..., switching. ;-)

--
Neil Cerutti
Dec 20 '05 #6
Pointers to functions are, at the least, a cleaner way of looking at
the code. I would also, think that they would be fastest since you're
directly calling it. I'll run a test today with the google profiler
tool thing and show you the results. (That is, of course, if gcc
behaves.)

Dec 20 '05 #7
*Please* quote relevant context of the message you are replying to.
Don't use the Reply button below the message in Google. Use the Show
Options button at the top and click Reply there.

OMouse wrote:
Pointers to functions are, at the least, a cleaner way of looking at
the code. I would also, think that they would be fastest since you're
directly calling it. I'll run a test today with the google profiler
tool thing and show you the results. (That is, of course, if gcc
behaves.)


<Original code repeated from upthread. It has errors but illustrates
the point.>

#include <iostream.h>
void choice1() , choice2() , choice3();

void (*do_choice [3]() = {choice1,choice2,choice3};

int main (void)
{
char ch;
cout << "make your choice : ";
cin >> ch;
cin.get();
ch -= '1 '; // arry starts on 0 , -1 for the right beginning
if (ch<0 || ch>2) cout << endl << "choice doesent exist !";
else do_choice[ch]();

return 0;
}

void choice1(void) { ...... }
void choice2(void) { ...... }
void choice3(void) { ...... }

I'm not sure about cleaner. It is not at all apparent in else
do_choice[ch](); which function is actually being called. You need to
refer to the the definition of the function pointer array. This may or
may not be a problem.

What is a problem is that this code only works if the decision of which
function to call is based on the value of an integer. That is also true
for a switch statement though, so presumably the OP is taking the
decision this way.

Gavin Deane

Dec 20 '05 #8
In addition to things already mentioned:

First It is unlikely that pointer-to-function will be faster for many
reasons. Second, you can't make pointer to inline function, your
compiler will probably instatiate the intended inline as callable
(after all inline is only a recommendation). Third, you can use inline
function in the loop just fine.

G.

vo******@gmail.com wrote:
I think pointers to functions are the fastest .
for example ...

#include <iostream.h>
void choice1() , choice2() , choice3();

void (*do_choice [3]() = {choice1,choice2,choice3};

int main (void)
{
char ch;

cout << "make your choice : ";
cin >> ch;
cin.get();
ch -= '1 '; // arry starts on 0 , -1 for the right beginning
if (ch<0 || ch>2) cout << endl << "choice doesent exist !";
else do_choice[ch]();
return 0;
}

void choice1(void) { ...... }
void choice2(void) { ...... }
void choice3(void) { ...... }

you can also put your functon inline ,
this will take up memoryspace but it will make your program run faster
.
you can never use an inline function in a loop .
This is not a good answer to your question but i hope you like my
alternative .

Greets.


Dec 20 '05 #9
I would argue that you can make if-else run faster for the cases when
one choice will be dominant. Making it the first choice will disrupt
execution pipeline less and may have huge payoff.

George

Dec 20 '05 #10
use an inline function yes , you wont get compiler errors .
but he ignores the inline call .

Dec 20 '05 #11
vo******@gmail.com wrote:
use an inline function yes , you wont get compiler errors .
but he ignores the inline call .


Who does? Please read the information in my .sig below. You've been
asked to follow this before, why haven't you?

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Dec 20 '05 #12
gp***@axonx.com wrote:
In addition to things already mentioned:

First It is unlikely that pointer-to-function will be faster for many
reasons.
What reasons?
Second, you can't make pointer to inline function, your
compiler will probably instatiate the intended inline as callable
(after all inline is only a recommendation). Third, you can use inline
function in the loop just fine.

G.


If your CPU is pipe-lined and has separate instruction and data cache paths,
an indirect function call can cost just one core clock. You can change the
actual function that gets called at run-time with a single word write to
cached data space, again at a cost of only one core clock.
Dec 21 '05 #13
1. For the reason that you have guaranteed bubble in the exec.
pipeline.
2. True, cache will take care of many things, but I am talking bubbles
mostly.

Dec 21 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Mike and Jo | last post by:
I've been converting some code to C++. I'm trying to use the Switch function to compare a result. Is it possible to use switch to evaluate '>0', '<0', 0? Example switch (result) { case...
10
by: clueless_google | last post by:
hello. i've been beating my head against a wall over this for too long. setting the variables 'z' or 'y' to differing numbers, the following 'if/else' code snippet works fine; however, the ...
17
by: prafulla | last post by:
Hi all, I don't have a copy of C standard at hand and so anyone of you can help me. I have always wondered how switch statements are so efficient in jumping to the right case (if any)? Can...
11
by: hasadh | last post by:
Hi, is the assemly code for if..else and switch statements similar. I would like to know if switch also uses value comparison for each case internally or does it jump to the case directly at...
18
by: swaroophr | last post by:
Which of switch statement and if-else statement takes less time to execute?
10
by: Evie | last post by:
I understand that when a switch statement is used without breaks, the code continues executing even after a matching case is found. Why, though, are subsequent cases not evaluated? I wrote a...
5
by: sam_cit | last post by:
Hi Everyone, I read somewhere that there are some compile time operations behind switch-case, which is why it can work for cases which evaluates to an integer or character and not strings and...
7
by: Rohit | last post by:
Hi, I am working on a switch module which after reading voltage through a port pin and caterogizing it into three ranges(open,low or high), passes this range to a function switch_status() with...
13
by: Satya | last post by:
Hi everyone, This is the first time iam posting excuse me if iam making any mistake. My question is iam using a switch case statement in which i have around 100 case statements to compare. so...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.