Web Development

General discussion


High Performance Software

By nsingh11172 ·
Is there any difference performance-wise between a switch and an
if-else statement? I need to choose between them for an important part
of my code that will have about 100 if-elseif statements or a switch
with 100 or so cases.

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Comments

Collapse -

by siddhant_kumar In reply to High Performance Software

certainly, a switch statement is on the order of 1 where as an if statement
is order(n). If you look at them both in a debugger, an if statement
examines each block until the block matches the condition, a switch
statement jumps directly to the correct condition. You may be able to
optimize an if statement by re-ordering the correct conditions to be higher
up the chain of conditions. It can only approach the speed of a switch
statement but never surpass it for all conditions. The downside of always
using a switch is that programmers abuse it. They contort it beyond what it
was meant for leading to sphaghetti code and maintenance nightmares.

If you liked the answer please rate it. and close your topic

bye for now

Siddhant Kumar

Collapse -

by nsingh11172 In reply to

Poster rated this answer.
Hi all this is well and all i know but i want to know compilers point of view at low level whatever you wrote i gree with that.

Collapse -

by DSR28 In reply to High Performance Software

Siddhant Kumar is not correct; BOTH switch and a large if() else if() scan the values one by one to find the right path. (There isn't a binary tree or anything else implemented in ANSI C to do this more effectively)

If you are building on a Pentium, or advanced processor with predictive path analysis or similar technology, try to keep the if else with the two most common items first. If the values are scattered evenly throughout (such as swith(char) where char is anything from 0 to 255), try to break the switch into sections and handle each case within(if char < 128 else if char >=12. Even then the predictor will only stall on the next switch.

Otherwise, (And my personal favorite solution!) create a lookup table of pointers to functions and populate it once upon initialization. Then, when you go to do the lookup, the lookup can handle the case really quickly, such as:
typedef struct __Lookup
FuncPtr Ptr;
} Lookup, *pLookup;

// populate the table somehow.
Lookup m_Lookup[] = {};

To do the lookup for value 5:
just call the function!
int iFunc = 5;

I have used that method often which only requires a couple of assembly statements in operation (pushing a memory location, and stack) and is quite simple and effective with predictive path operations in processors. JUST MAKE SURE TO DOUBLE CHECK THE INTEGER TO ENSURE IT DOESN'T WALK OVER THE END OF YOUR STRUCTURE!

I hope this helps.

Related Discussions

Related Forums