Testing with the Visual Studio 11 Developer Preview reveals that if your switch statement has fewer than 7 cases (6 cases and a default), then the compiler generates a series of if
statements. Your example code is converted to the equivalent of:
string s = abc.ToLower();
if (s == "123") return "Numeric";
if (s == "ab") return "Alphabetic";
return "symbol";
If there are 7 or more cases, the compiler generates code that creates a dictionary, mapping strings to sequential integers. It then uses an IL switch
statement (which similar to a computed goto in other languages) to branch to the different code based on the values.
The code is generated such that the dictionary is only created once--the first time the switch statement is executed. Subsequent uses of that switch statement don't have to re-create the dictionary.
In terms of efficiency, the compiler's code generated for a small switch statement is equivalent to multiple if statements. When there are more than a 6 cases (including the default), the compiler's dictionary lookup will be faster than the multiple switch statements.
Note that my numbers are based on a very small sample (a few tests) using the developer preview of an unreleased version of the compiler. Previous versions of the compiler might have a different threshold or might use other methods, and the final release version of the new compiler might do things differently than what I've described above. I wouldn't count on any of these implementation details.
In short, write the switch
. Let the compiler worry about how to make it faster.