Case vs If Else If: Which is more efficient?

PerformanceSwitch StatementIf Statement

Performance Problem Overview


> 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{

   }

Performance Solutions


Solution 1 - Performance

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

Solution 2 - Performance

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.

Solution 3 - Performance

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.

Solution 4 - Performance

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

Solution 5 - Performance

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.

Solution 6 - Performance

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

Solution 7 - Performance

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.

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
QuestionAran MulhollandView Question on Stackoverflow
Solution 1 - PerformanceYvoView Answer on Stackoverflow
Solution 2 - PerformanceGuffaView Answer on Stackoverflow
Solution 3 - PerformanceRyanView Answer on Stackoverflow
Solution 4 - PerformancemlatheView Answer on Stackoverflow
Solution 5 - PerformanceNate HeinrichView Answer on Stackoverflow
Solution 6 - Performancemcintyre321View Answer on Stackoverflow
Solution 7 - PerformanceCorbin MarchView Answer on Stackoverflow