Does the order of case in Switch statement can vary the performance?

Bipul picture Bipul · May 12, 2010 · Viewed 9.9k times · Source

Let say I have a switch statement as below

switch(alphabet) {

    case "f":
        //do something
        break;

    case "c":
        //do something
        break;

    case "a":
        //do something
        break;

    case "e":
        //do something
        break;

}

Now suppose I know that the frequency of having Alphabet e is highest followed by a, c and f respectively. So, I just restructured the case statement order and made them as follows:

switch(alphabet) {

    case "e":
        //do something
        break;

    case "a":
        //do something
        break;

    case "c":
        //do something
        break;

    case "f":
        //do something
        break;
}

Will the second switch statement be faster than the first switch statement? If yes and if in my program I need to call this switch statement say many times, will that be a substantial improvement? Or if not in any how can I use my frequency knowledge to improve the performance?

Answer

Dean Harding picture Dean Harding · May 12, 2010

Not so much that you should be concerned. It's certainly not something that can be predicted.

With string case labels, the compiler actually uses an internal hash table that maps the strings to indexes in a jump-table. So the operation is actually O(1) - independent of the number of labels.

For integer labels, then I believe the actual code that is generated depends on the number of labels and whether the numbers are consecutive (or "almost" consecutive). If they're consecutive (1, 2, 3, 4, ...) then they'll just be transformed into a jump table. If there's a lot of them, then the Hashtable+jump table (like with strings) will be used. If there's only a few labels and they're not table to be immediately transformed into a jump table, only then will be transformed into a series of if..then..else statements.

In general, though, you should write code so that you can read it, not so that the compiler can produce "faster" code.

(Note my description above is an implementation detail of how the C# compiler works internally: you shouldn't rely on it always working like that -- in fact, it might not even work exactly like that now, but at least it's the general idea).