to switch-case or not to !

A friend (and colleague) in an attempt to have a long discussion asked me about my preference between cascaded if-else and switch-case statements and which one is better. I could get away (because was caught into some work I didn’t want to lose attention from) by saying that I will certainly be getting back with facts you want to know and my personal preference is switch-case.

Later in the evening (now) I am in front of firefox with almost seventeen tabs open with
links relating to the comparison between if-else and switch-case statements. I think I should share some statements here (sources are documents and forums available on internet).

The switch-case can only used with integral types, and the case values need to be compile-time constants. An if/else cascade is likely to be slower than switch/case.

switch/case is often implemented using a jump table with the case values as index into the table. The if/else is usually implemented using a cascade of conditional jumps. Hence switch/case often will win on time efficiency.

The best construct to use is the one that is the easiest to understand to the reader (and not the more efficient) (obviously, if it is not killing the program).

For the curious,

A jump table is either a table of addresses (pointers) or jump instructions. An index is used to access the appropriate location, then an action is taken. This can be implemented in C++ using an std::map of <key, function_pointer> or an array of similar structures.

3 Responses

  1. switch in C, as you say, can only take constant expressions for the case labels. switch in JavaScript can take arbitrary expressions (for example, strings “foo”, conditionals x > y, computed expressions x*x).

  2. Thanks for the information. My comment was (very much) limited to C/C++ (as my exposure is). But had I mentioned that, enlightenment with this revelation would not have happened.

    Read your blog, Nice posts.

    -Manoj

  3. I have coded some jump tables in assembly before. I would say they are more efficient than if-else cascades. If switch structures are implemented with strings (as in Java) my guess is they would be about the same speed as if-else cascades ( maybe faster still depending on how they do the strcmp ).

    As it turns out, I am using switch structures to speed up a program I am writing right now. ( I had just googled my way here looking for if the compiler implements them as jump tables or not ).

Leave a Reply

You must be logged in to post a comment.