views:

130

answers:

3

Does the time taken by a switch statement (or jump table in compiled form) to "decide" where to jump rise by the number of casees it contains?

+3  A: 

Not really, there's usually a hash table or some other O(1) lookup data structure in the compiled code (unless you only have a tiny amount of switches, then the compiler may decide to use jumps instead). In general a large amount of switches should outperform a large amount of if statements, although normally you wouldn't have enough cases for it to be noticeable anyways.

Longpoke
+6  A: 

It depends on the compiler and (typically) the values you supply -- if the values are "dense" (i.e., all or almost all values in a range have cases in the switch statement) you'll typically get a jump table, which takes the same time for all values (in that range). If you have relatively sparse values, it may compile to code roughly equivalent to an if/then/else ladder, in which case adding more (sparse) case values can increase execution time.

Jerry Coffin
+2  A: 

Why are you interested in that? That's a very low-level micro-optimization, which is very unlikely to yield any noticeable performance improvement, unless you have a very wickedly tweaked algorithm with every last nanosecond already squeezed out of it.

If you have a specific case, where you have proven that a switch indeed is an important bottleneck, don't ask us (what do we know about your compiler, memory, processor etc.?), but measure yourself, using the tools you are using, in the environment you code is supposed to run.
In every other case just go on coding and try to write the code so that it is a readable as possible, instead of doing premature optimization.

sbi
there's no harm in being *interested* in how the compiler treats your code. Curiosity doesn't make you a bad programmer, and the OP has said nothing to indicate that this is a premature optimization (that assumes both that the OP is willing to *make* the optimization, and is not just asking to satisfy his curiosity, and that it is premature, ie. that he doesn't yet know if it is a performance bottleneck)By all means point out that it's unlikely to matter. But don't answer the question with some kind of religious mantra that it's somehow "dangerous" to even think about this question.
jalf