Does .Net 4 (or any prior version) perform any sort of optimization on longer switch statements based on strings?
I’m working around a potential performance bottleneck due to some long switch statements looking for matching strings in the cases, and I’ve always assumed these are searched in linear time (or near linear, i.e. not using an index to quickly find the matching string). But this seems like an obvious area that .Net could optimize, so thought I’d check if this is the case or not.
This is a derivative question from my recent one: indexed switch statement, or equivalent? .net, C#
Compile the following code.
Now use Reflector or ILDASM to examine the IL the C# compiler generates. Keep adding case statements and decompiling and observe the result.
Dictionarylookup.I was using the C# 3.0 compiler and I observed that the strategy changes at 7 case statements. I suspect you will see something similiar with C# 4.0 and others.
Update:
I should point that you will see calls to
Dictionary.Addin the IL output where it is building up the dictionary for later use. Do not be fooled into thinking this happens everytime. The compiler is actually generating a separate static class and doing an inline static initialization of it. Pay particular attention to the instruction at L_0026. If the class is already initialized then the branch will skip over theAddcalls.Also, notice that the dictionary actually contains a map from the original string to an integer. This integer is used to formulate a separate switch in IL.
Update 2:
For what it is worth VB.NET does not seem to have this same optimization for its
Selectconstruct.