[performance] Case vs If Else If: Which is more efficient?

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{

   }

This question is related to performance switch-statement if-statement

The answer is


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

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.


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


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.


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.


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.


Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA