70

Possible Duplicates:
is “else if” faster than “switch() case” ?
What is the relative performance of if/else vs. switch in Java?

Ive been coding-in-the-run again....when the debugger steps through a case statement it jumps to the item that matches the conditions immediately, however when the same logic is specified using if/else it steps through every if statement until it finds the winner. Is the case statement more efficient, or is my debugger just optimizing the step through? (don't worry about the syntax/errors, i typed this in SO, don't know if it will compile, its the principle i'm after, I didn't want to do them as ints cause i vaguely remember something about case using an offset with ints) I use C#, but im interested in a general answer across programming languages.

switch(myObject.GetType()){

    case typeof(Car):
        //do something
        break;

    case typeof(Bike):
        //do something
        break;

    case typeof(Unicycle):
        //do something
        break;

    case default:
        break;
}

VS

   Type myType = myObject.GetType();

   if (myType == typeof(Car)){
            //do something
   }

   else if (myType == typeof(Bike)){
            //do something
   }

   else if (myType == typeof(Unicycle)){
            //do something
   }
   else{

   }
Community
  • 1
  • 1
Aran Mulholland
  • 23,555
  • 29
  • 141
  • 228
  • 11
    This isn't even *close* to being language-agnostic, any answer is going to be tightly bound to one specific language. – skaffman Jan 28 '10 at 23:25
  • 5
    not to mention specific compiler and compiler version. – Pascal Cuoq Jan 28 '10 at 23:27
  • It may vary between languages, compilers and runtimes. No way to know for sure. – FrustratedWithFormsDesigner Jan 28 '10 at 23:29
  • This isn't even language-specific. It depends entirely on a particular compiler implementation and possibly isn't 100% answerable even then (e.g. maybe some forms of if-statements are optimized differently than others). – Chuck Jan 28 '10 at 23:29
  • Similar question in Java perspective: http://stackoverflow.com/questions/2086529/what-is-the-relative-performance-of-if-else-vs-switch-in-java – BalusC Jan 28 '10 at 23:45
  • 1
    BTW: the *real* answer to this question is to have them all implement a common interface/abstract method, e.g. `Vehicle#doSomething()` and have each definied in the concrete implementation **itself**, so that you just end up with `myObject.doSomething()`. – BalusC Jan 29 '10 at 00:07
  • Php, if/else is faster given the way it's parsed. – David Hobs Sep 29 '12 at 02:27
  • Use `switch` if you are strictly trying to match a variable against a list of possible values (more than 2). Use `if else` for other scenarios. That way if you see a block of switch statement you immediately know what the purpose of the code is. – BigName Dec 17 '21 at 22:08

7 Answers7

104

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

Yvo
  • 18,681
  • 11
  • 71
  • 90
  • 1
    I don't understand this part "You could be calling methods in the if-statements, influencing variables" How could this happen in a if else ? I think that is the same. – Castelmager Sep 12 '16 at 13:48
  • 1
    You can do if (++i) { .... }, but you cannot do that in a switch case statement. – Granada Dec 09 '16 at 16:09
8

The debugger is making it simpler, because you don't want to step through the actual code that the compiler creates.

If the switch contains more than five items, it's implemented using a lookup table or hash table, otherwise it's implemeneted using an if..else.

See the closely related question is “else if” faster than “switch() case” ?.

Other languages than C# will of course implement it more or less differently, but a switch is generally more efficient.

Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
7

Many programming language optimize the switch statement so that it is much faster than a standard if-else if structure provided the cases are compiler constants. Many languages use a jump table or indexed branch table to optimize switch statements. Wikipedia has a good discussion of the switch statement. Also, here is a discussion of switch optimization in C.

One thing to note is that switch statements can be abused and, depending on the case, it may be preferable to use polymorphism instead of switch statements. See here for an example.

Ryan
  • 7,835
  • 2
  • 29
  • 36
0

i think it's just the debugger making it simple. Note that a case and "if list" are not ultimately the same. There is is a reason why case blocks normally end with "break". The case stmt actually looks something like this when broken down in assembly.

if myObject.GetType() == type of Car
    GOTO START_CAR
else if myObject.GetType() == type of Bike
    GOTO START_BIKE

LABEL START_CAR
//do something car     
GOTO END

LABEL START_BIKE
//do something bike  
GOTO END

LABEL END

If you don't have the break, then the case blocks would be missing the "GOTO END" stmts, and in fact if you landed in the "car" case you'd actually run both sections

//do something car     
//do something bike  
GOTO END
mlathe
  • 2,375
  • 1
  • 23
  • 42
0

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

Nate Heinrich
  • 1,805
  • 14
  • 14
0

it can do this for case statements as the values are compiler constants. An explanation in more detail is here http://sequence-points.blogspot.com/2007/10/why-is-switch-statement-faster-than-if.html

mcintyre321
  • 12,996
  • 8
  • 66
  • 103
0

Wikipedia's Switch statement entry is pretty big and actually pretty good. Interesting points:

  • Switches are not inherently fast. It depends on the language, compiler, and specific use.
  • A compiler may optimize switches using jump tables or indexed function pointers.
  • The statement was inspired by some interesting math from Stephen Kleene (and others).

For a strange and interesting optimization using a C switch see Duff's Device.

Corbin March
  • 25,526
  • 6
  • 73
  • 100