By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,928 Members | 1,200 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,928 IT Pros & Developers. It's quick & easy.

Switch vs. Else If

P: n/a
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
Share this Question
Share on Google+
13 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
*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

P: n/a
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

P: n/a
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

P: n/a
use an inline function yes , you wont get compiler errors .
but he ignores the inline call .

Dec 20 '05 #11

P: n/a
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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.