473,378 Members | 1,347 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,378 software developers and data experts.

switch vs. if

Hello all,

Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?

Thanks,
Dave
Jul 22 '05 #1
8 6794
Dave wrote:
Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?


It is probably true. I've never written an optimizing C++ compiler, so
I can't say I know what's involved. But it does seem that a 'switch'
statement with its very direct and straightforward approach would be
actually easier to implement as a table than an 'if' statement. Besides,
the 'switch' cannot really be screwed up by sudden introduction of some
arbitrary expression (during code maintenance, I mean).

V
Jul 22 '05 #2
Dave wrote:
Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?


No. Any half-decent compiler will reduce a switch statement to a jump
table, which is O(1) to the number of cases (assuming the cases are
sequential). A series of if-else statements will be reduced only by an
exceedingly clever compiler, and if compiled in the usual way will be O(n)
to the number of cases. An if statement will produce code with size
proportional to the number of cases, whereas a switch statement may produce
a very large mostly-empty table if the cases are sparse (depending on your
compiler.)

In fact, a switch statement is conceptually much more like a jump table
than like a series of if-else statements. Consider Duff's Device, for example:
switch(count%8){
case 0: do{ *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
}while(--n>0);
}

--
CalcRogue: TI-89 and TI-92+. <http://www.gis.net/~wssddc/jimmy_b/>.
Jul 22 '05 #3
"Dave" <be***********@yahoo.com> wrote in message
news:10*************@news.supernews.com...
Hello all,

Consider the case of an if with many else if clauses vs. a switch with many cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?


I advise not worrying about 'performance', but to write
the code to be as clear and readable as possible. Make
the code maintainable. Programmer time is far more
expensive than computer time.

IMO two or three conditions would probably be best served
with 'if' and 'else', whereas more conditions than than would
probably be most clearly expressed with a 'switch'. And
if the number of conditions becomes excessive, consider
e.g. a table of function pointers (perhaps stored in a
std::map).

Only concern yourself with optimization after you've
empirically proven that the code's performance is
unacceptable. If that is the case, then use a profiler
to find out where the slowdowns really are (they're
frequently not where you'd think). An improvement in
performance is more typically gained by optimizing
the 'higher level' algorithm(s) than messing around
with 'micro-optimizations', which imo is the job of
the compiler.

-Mike
Jul 22 '05 #4
Dave wrote:

Hello all,

Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?

Thanks,
Dave


For some reason I always expected the compilers to optimise a long switch
statement by using binary search. Now, the interesting part is that
gcc 3.3.3 appears to do exactly that (O(log n)), unless the range of values
is compact, in which case it uses a table (O(const)).
The if statement, on the other hand, in my tests was implemented literally,
without any clever optimisation.

For long selection lists the difference can be measurable. Though it comforts
me to think of it as of a potential bonus, I'd pick a switch over if whenever
appropriate regardless of the performance.

Denis
Jul 22 '05 #5
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:5s8yc.1154
I advise not worrying about 'performance', but to write
the code to be as clear and readable as possible. Make
the code maintainable. Programmer time is far more
expensive than computer time.
Usually, switch case looks better to me, but I've gotten used to both ways.
For complex cases, it's best to use the command pattern, where there are
many objects and each implements a virtual function defined as pure virtual
in the base class.

IMO two or three conditions would probably be best served
with 'if' and 'else', whereas more conditions than than would
probably be most clearly expressed with a 'switch'. And
if the number of conditions becomes excessive, consider
e.g. a table of function pointers (perhaps stored in a
std::map).
Right, or the command pattern.

Only concern yourself with optimization after you've
empirically proven that the code's performance is
unacceptable. If that is the case, then use a profiler
to find out where the slowdowns really are (they're
frequently not where you'd think). An improvement in
performance is more typically gained by optimizing
the 'higher level' algorithm(s) than messing around
with 'micro-optimizations', which imo is the job of
the compiler.


Jul 22 '05 #6
Denis Remezov wrote:
Dave wrote:
Hello all,

Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?

Thanks,
Dave

For some reason I always expected the compilers to optimise a long switch
statement by using binary search. Now, the interesting part is that
gcc 3.3.3 appears to do exactly that (O(log n)), unless the range of values
is compact, in which case it uses a table (O(const)).
The if statement, on the other hand, in my tests was implemented literally,
without any clever optimisation.

For long selection lists the difference can be measurable. Though it comforts
me to think of it as of a potential bonus, I'd pick a switch over if whenever
appropriate regardless of the performance.

Denis


Zilog's old Z8000 compilers took advantage of the instruction set and generated
a jump table even for noncontiguous values.
Jul 22 '05 #7
Dave wrote:
Hello all,

Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.

Would others agree that this is true for "typical" implementations?

Thanks,
Dave


Hmmm, remember the third alternative. (I.e. most of the timer there
is always a third alternative, not just black or white.)

One can also implement a jump table (a table of function pointers),
instead of the above. On benefit to the table drive approach is
that the executable code doesn't need to be retested; the data
is changed not the driver. On the other hand, there are cases
where the table can be used as premature optimization (in which
your wasting programming time for a construct that the compiler
will automatically generate).

I've just learned, the hard way, about converting all switch
statements into function tables. Sometimes, switch statements
can be a lot easier to read than a function table.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #8
On Thu, 10 Jun 2004 16:07:48 -0700, "Dave" <be***********@yahoo.com>
wrote:
Hello all,

Consider the case of an if with many else if clauses vs. a switch with many
cases.

In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.
Not true. The switch expression need be evaluated only once, whereas
each if expression must be independently evaluated (or at least enough
of it to return its Boolean result).
Would others agree that this is true for "typical" implementations?


I suppose one could generate an assembly listing from a "typical"
compilation and examine the way the compiler has done it. "Typical"
doesn't necessarily mean anything, does it?

As someone else pointed out, you can usually do away with both if you
have properly designed your classes with virtual functions.
--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #9

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

Similar topics

14
by: Rudi Hansen | last post by:
I dont seem to be able to find the switch statement in Python. I would like to be able to do switch(var) case 1 : print "var = 1" case 2: print "var = 2"
10
by: Myster Ious | last post by:
Polymorphism replaces switch statements, making the code more compact/readable/maintainable/OO whatever, fine! What I understand, that needs to be done at the programming level, is this: a...
5
by: Bryan Parkoff | last post by:
C++ programmers and I tried to experience by writing 65536 switch cases. It is too large for Windows XP and other operating system to handle. It looks like that JMP Table obtains 256K bytes for...
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 ...
65
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? ...
3
by: pgraeve | last post by:
I am a convert from VB to C# so bear with me on this "conversion" question C# switch statement seems to be the closest relative to VB's Select Case. I used VB's Select Case statement liberally. ...
11
by: ME | last post by:
In C# the following code generates a compiler error ("A constant value is expected"): public void Test(string value) { switch (value) { case SimpleEnum.One.ToString(): MessageBox.Show("Test...
12
by: | last post by:
Is it fine to call another method from Switch? Eg. Switch (stringVar) { case ("a"): somVar = "whatever"; Another_Method(); //call another method return;
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...
11
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
Can switch statements be nested? I've got a large routine that runs off of a switch statement. If one of the switches in switch #1 is true, that enters switch statement #2. Some of the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.