Why the switch statement and not if-else?

If StatementLanguage AgnosticSwitch Statement

If Statement Problem Overview


I've been wondering this for some time now. I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations. For the real question: What is the point of the switch statement? Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

https://stackoverflow.com/users/10661/s-lott">S.Lott</a> has pointed out that this may be a duplicate of questions https://stackoverflow.com/questions/395618/if-else-vs-switch">If/Else vs. Switch. If you want to close then do so. I'll leave it open for further discussion.

If Statement Solutions


Solution 1 - If Statement

A switch construct is more easily translated into a [jump (or branch) table][1]. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation.

Below are some extremely simplified psuedo-assembly examples. First, the if-else version:

    // C version
    if (1 == value)
        function1();
    else if (2 == value)
        function2();
    else if (3 == value)
        function3();

    // assembly version
    compare value, 1
    jump if zero label1
    compare value, 2
    jump if zero label2
    compare value, 3
    jump if zero label3
label1:
    call function1
label2:
    call function2
label3:
    call function3

Next is the switch version:

    // C version
    switch (value) {
    case 1: function1(); break;
    case 2: function2(); break;
    case 3: function3(); break;
    }

    // assembly version
    add program_counter, value
    call function1
    call function2
    call function3

You can see that the resulting assembly code is much more compact. Note that the value would need to be transformed in some way to handle other values than 1, 2 and 3. However, this should illustrate the concept. [1]: http://en.wikipedia.org/wiki/Jump_table

Solution 2 - If Statement

Switch can be optimized by compiler - you will get faster code.
Also I find it to be more elegant when dealing with enumerable types.

To sum up switch statement gives you performance + code elegance :)

Here are some useful links:

Solution 3 - If Statement

For expressiveness, the switch/case statement allows you to group multiple cases together, for example:

case 1,2,3: do(this); break;
case 4,5,6: do(that); break;

For performance, compilers can sometimes optimize switch statements into jump tables.

Solution 4 - If Statement

I'm ignoring this type of low level optimization as usually unimportant, and probably different from compiler to compiler.

I'd say the main difference is readability. if/else is very flexible, but when you see a switch you know right away that all of the tests are against the same expression.

Solution 5 - If Statement

Besides the other mentioned Code readability and optimisation in .NET you also get the ability to switch on enums etc

enum Color { Red, Green, Blue }; 

Color c = Color.Red;

switch (c) // Switch on the enum

{

// no casting and no need to understand what int value it is

case Color.Red:    break;
case Color.Green:  break;
case Color.Blue:   break;

}

Solution 6 - If Statement

The ability to fall through several cases (intentionally leaving out the break statement) can be useful, and as a few people have already said it's faster as well. Perhaps the most important and least important consideration though, is that it just makes for prettier code than if/else. :)

Solution 7 - If Statement

Switch can be optimized "Better" by some compilers. There are pitfalls with using the switch statement in certain languages. In Java, the switch cannot handle strings and in VB2005 the switch statement will not work with radio buttons.
Switch can be faster and easier to read, If-Then is more generic and will work in more places.

Solution 8 - If Statement

The only time switches can be faster are when your case values are constants, not dynamic or otherwise derived, and when the number of cases is significantly larger than the time to calculate a hash into a lookup table.

Case in point for Javascript, which compiles to assembly for execution on most engines, including Chrome's V8 engine, is that switch statements are 30%-60% slower to execute in the common case: http://jsperf.com/switch-if-else/20

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNopeView Question on Stackoverflow
Solution 1 - If StatementJudge MaygardenView Answer on Stackoverflow
Solution 2 - If StatementakuView Answer on Stackoverflow
Solution 3 - If StatementjdigitalView Answer on Stackoverflow
Solution 4 - If StatementDarronView Answer on Stackoverflow
Solution 5 - If StatementJustin KingView Answer on Stackoverflow
Solution 6 - If StatementMarc CharbonneauView Answer on Stackoverflow
Solution 7 - If StatementWolfmanDragonView Answer on Stackoverflow
Solution 8 - If StatementAnthony HildoerView Answer on Stackoverflow