473,624 Members | 2,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switch and if..else same at assemby code ?

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 the assembly level ?

for a performance critical application is it better to to use switch
case or
accomplish the same using fn pointers ?
please advice.

Thanks for your time.
prakash
Nov 14 '05 #1
11 3755
Hello
is the assemly code for if..else and switch statements similar.
Not all the time. Depends on the compiler and the switch values.
I would like to know if switch also uses value comparison for each case
internally or does it
jump to the case directly at the assembly level ?
In most cases, the compiler generates a switch jump table.
Basically comprised of two tables: values table and code offset table.
That is faster than if/else statments.

You will better understand this if you take debug your own sample program
that uses switch statement.

However, if the switch values are not in some sort of sequence the compiler
might generate an ASM code that looks like a serie if/else.

I am referring to code I've seen generated by C compilers on Intel x86
machines.
for a performance critical application is it better to to use switch
case or
accomplish the same using fn pointers ?
Even if you use function pointers, you would have to write a code that maps
a given value to a given index in the function pointers table.
Somehow similar to compiler's generated code.
please advice.


You'ld better ask this question again in comp.lang.asm.x 86 or alt.lang.asm

Hope that helps,
Elias
Nov 14 '05 #2
In article <7b************ *************@p osting.google.c om>,
hasadh <h_****@hotmail .com> wrote:
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 the assembly level ?
It depends on the implementation. Quite likely it will compile to a jump
table if all (or most) of the values are contiguous, and use conditionals
if they aren't. Even a jump table will probably have to compare the
control variable against the range of values, unless you use all the values
allowed by the type (e.g. 256 cases switching on an 8-bit char).
for a performance critical application is it better to to use switch
case or accomplish the same using fn pointers ?


Again, it depends on your implementation and what you're doing. If
you don't have lots of state to pass around, function pointers are
quite natural, but for something like a virtual machine it will often
be faster to use a big switch, or perhaps a non-standard extension (in
particular, the ability to assign labels to a variable).

-- Richard
Nov 14 '05 #3
hasadh wrote:
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 the assembly level ?

for a performance critical application is it better to to use switch
case or
accomplish the same using fn pointers ?
please advice.

Thanks for your time.
prakash


There is a balance between generating huge jump tables
or generating too many if/else constructs when implementing
a switch statement in assembly code.

In the lcc-win32 compiler this is determined by a "density" parameter,
that starts with a default value of 0.5.

The user can control this parameter using a
#pragma density
construct.

This allows you to force the compiler to generate
jump tables even if the switch case values aren't contiguous. In
a time critical place of the application you can trade space for speed
by forcing the compiler to build a jump table using
#pragma density(0).

If you want to minimize data space usage you can turn all
switch statements into a series of if/else statements by setting
#pragma density(1.0)

References
----------
Fraser and Hanson A retargetable C compiler
http://www.amazon.com/exec/obidos/tg...glance&s=books
Nov 14 '05 #4
hasadh wrote:
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 the assembly level ? Depends on the processor and the compiler writer.

Some processors have specialized instructions for jump tables. Some
processors can conditionally execute instructions. Since there is no
uniform assembly language, there is a lot of dependency on the processor
type.

There is also a lot of variance left for the compiler writer. Some
compilers can optimize an if-else-if ladder better than using a jump
table. Some may automatically convert a switch statement into a jump
table. Others may allow leeway through the use of compiler switches.

The best that you can do is to have the compiler(s) that you use print
the suspect code in assembly language. Print it out for every
optimization setting. Choose the compiler switches that generate the
best assembly language.


for a performance critical application is it better to to use switch
case or accomplish the same using fn pointers ?
please advice.

Depends on where the bottleneck is.
Have you profiled the code?

Here are my suggestions:
1. Use switch or an if-else ladder depending on what makes the
program more readable.

2. Worry about correctness before optimizing.

3. Profile the code to find out where the bottlenecks are.
Profile more than once. Many programs operating behavior
depends on other programs that are executing concurrently.

4. Don't second guess the compiler. Print out the assembly language
to find out how the compiler optimized the code. Use this as
a basis for any optimizing.

5. Every situation is different. One part of the code may be
more efficient using if-else ladders. Another code may be
more efficient using switches. The coding guidelines of a
software house may mandate switch statement over if-else
(even over efficieny).

6. If you believe a jump table is more appropriate, you can always
create one using the C language.

7. If your to the point of recoding a module for efficiency,
consider writing that module in assembly.

8. Don't optimize unless absolutely necessary. You are wasting
time and money tweaking the code. There are always risks of
problems popping up every time the code is altered. Even
though the changes you make in your function don't explicitly
change the rest of the program, chances are that some other
function may be effected (such as code or constants being
moved so they aren't aligned anymore).
--
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.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #5
# 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 the assembly level ?

Implementation dependent. Both can be translated into 'if (predicate) goto label;'
and for all we know that might be exactly what the compiler does so that its code
generator sees no difference.

# for a performance critical application is it better to to use switch
# case or
# accomplish the same using fn pointers ?

In general there's no way to predict whether if or switch will be faster. Nor even
function calls. But for most implementations , function calls which cannot be inlined
and even more so function pointers will be slower. But even in this there can be
exceptions. Usually function calls and pointers impede analysis by optimisers and
break code locality for caches and vm.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Death is the worry of the living. The dead, like myself,
only worry about decay and necrophiliacs.
Nov 14 '05 #6
kal
"lallous" <la*****@lgwm.o rg> wrote in message news:<2q******* *****@uni-berlin.de>...
In most cases, the compiler generates a switch jump table.
Basically comprised of two tables: values table and code offset table.
That is faster than if/else statments.


It is not necessarily faster. It could be slower if the
values are few and discontinuous.
Nov 14 '05 #7
In article <7b************ *************@p osting.google.c om>,
h_****@hotmail. com (hasadh) wrote:
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 the assembly level ?

for a performance critical application is it better to to use switch
case or
accomplish the same using fn pointers ?
please advice.


If the application is performance critical, then you should just try
different approaches and measure how long each one takes.

What you want to do is called "micro-optimisation" and will rarely lead
to faster code. If you want fast code, start by writing your code so
that it is as readable as possible and as easy to maintain as possible.
That way you will arrive at working, bug-free code earlier. Only then,
when you have code that actually works, can you find out what is
performance critical - if you try to decide about that before your code
is working, you are only guessing and most likely you will be wrong, and
waste your time by trying to make code faster that doesn't need to be
made faster.

Another hint: How many cycles does a Pentium 4 running at 3000 MHz take
to read a single byte from uncached memory? I recommend you try to find
the answer and then think about it for a while.
Nov 14 '05 #8
hasadh wrote:
for a performance critical application is it better to to use switch
case or accomplish the same using fn pointers ?


If you're using a modern optimizing compiler, then it will be very
careful to pick the best way of compiling a switch, in order to maximize
efficiency while not producing an excessively large jump table. Use
switches and depend on the compiler to do the best thing; generally it
is whether you think it is or not. Following are some of the techniques
it uses - if you must optimize, don't try to optimize any switch in your
own code until you've established for sure that it's a bottleneck with
profiling tools.

First of all, whenever the number of cases is small, meaning less than
20 or so, the code produced will almost always mimick that produced by
simple if-else branching, because this is the fastest way. Jump tables
do not benefit speed in such cases because of the time needed to load
from the table, and this includes almost all switch statements written
by hand in typical programs.

In another simple case, where the cases of the switch fill or nearly
fill a large enough contiguous range (like 1 through 50 except 13 and
27), a simple jump table would be generated. The compiler uses a density
heuristic to evaluate how "filled" the range is.

If there are a large number of values, say 200, spread widely across a
very large range, say the entire range of a 32-bit integer, then the
jump table solution is no good. A good solution in this case is to hash
the value being switched on to an index between 0 and 199, jump to the
address at this index in the jump table, and then resolve collisions, if
any, inside the case handler with if-else branching. If the compiler can
generate a perfect hash function, this is even better, as no collision
resolution is necessary. This case doesn't appear much in practice, and
so compilers don't usually deal with it. If you have a switch like this
in your code, you may want to write a preprocessing tool to emit code
which switches on the hash, has contiguous case labels, and does
collision resolution appropriately.

Finally, there's a common scheme that conditionals with jump tables: it
identifies a small number of dense ranges among the cases, decides which
range the value is in using if-else branching, then uses a jump table
within the range. This would be useful if your cases were, for example,
'0' through '9' and 'a' through 'z'. This one isn't always implemented
by compilers. If yours doesn't do it, write a separate switch statement
for each dense range of cases, and choose between them with if-else.
This has the same effect.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #9
Some small corrections:

Derrick Coetzee wrote:
If there are a large number of values, say 200, spread widely [ . . . ]
hash the value being switched on to an index between 0 and 199, [ . . . ]
This is if you're using a perfect hash. If you're using a less perfect
hash, you probably want the jump table size to be about 25-50% bigger
than the number of values (to reduce collisions).
Finally, there's a common scheme that conditionals with jump tables [ . . . ]


Meant: Finally, there's a common scheme that *combines* conditionals
with jump tables

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #10

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

Similar topics

15
7596
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 (>0): case (<0):
1
1253
by: Andy | last post by:
I am building a large enterprise application and which to implement a nested namespace hierarchy across the application. My problem is that when I declare an assembly "MyApp.DataTypes" in one assemby and then another "MyApp.GUITypes" in another I cannot access types in the "...DataTypes" namespace from the Assembly containing the "...GUITypes" namespace. The documentation suggests this should be possible. Do I need to use aliases.
10
9567
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 'case' code snippet does not. (the code's function is illustrative.) ////////////////////////////////////////// //////// working 'if/else' switch //////// //////////////////////////////////////////
18
3058
by: swaroophr | last post by:
Which of switch statement and if-else statement takes less time to execute?
13
7540
by: Michael Griebe | last post by:
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,...
10
12313
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 program to demonstrate how a switch without breaks behaves vs. how I expected it to behave. The code includes: (1) a switch statement with breaks (2) the if/else statements that have the same results as (1) (3) a switch statement without breaks...
22
3156
by: John | last post by:
Hi Folks, I'm experimenting a little with creating a custom CEdit control so that I can decide on what the user is allowed to type into the control. I started off only allowing floating point numbers then added support for putting in lat/lon coordinates. I tried this little piece of code inside the OnChar function but compiler complained about missing ';' after "case _T('W'):"
7
3355
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 parameters value and signal ID. Signal Id is used to get a user configurable parameter inside a configuration file, which depends on the type of switch. I have implemented it as under. Please ignore those magic numbers as I have mimized logic to...
13
11806
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 just curious to find out is it effective to use this method?? or is there is any other alternative method present so that execution time and code size can be reduced?? Thanks in advance.
0
8168
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8672
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8330
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8471
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6107
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4075
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2603
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1474
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.