473,439 Members | 1,894 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,439 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 6798
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.