The order of C# switch case statements in your code has no effect on performance.

The C# switch…case statement is good for selecting one branch of execution from a set of mutually exclusive ones.  The values in each case statement must be constant.  This allows the CLR to optimize the switch statement at compile time since the case values are known.

Consider the following example:

string fruit = this.GetFruit();
switch (fruit)
{
    case "Apple":
        apples++;
        break;
    case "Banana":
        bananas++;
        break;
    case "Lemon":
        lemons++;
        break;
    case "Peach":
        peaches++;
        break;
}

You might think the switch statement translates into a series of if-else blocks as follows:

if (fruit == "Apple")
    apples++;
else if (fruit == "Banana")
    bananas++;
else if (fruit == "Lemon")
    lemons++;
else if (fruit == "Peach")
    peaches++;

But this is not the case.  In .NET, switch statements are usually optimized for the data type.  Meaning that a switch on strings is likely implemented as a hash table.  And a switch on integers may be implemented as a lookup array.  (read more)

Therefore, the order of your case statements has no effect on the final code.  Instead, you should list the case statements in an order that makes sense to human readers of your code (e.g., alphabetical order for string case statements).

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot