I have read in various places that switch statements with string cases can potentially be optimized (by the compiler or the JIT) into hash tables to improve performance. Hash tables with non-perfect hashing functions obviously do not guarantee item order, and so I was wondering:
- Can the C# compiler or the JIT perform an optimization that converts a
switchstatement to a hash table to provide constant-time performance? - Do
switchstatements in C# guarantee that thecase‘s are checked in order, from top to bottom?
No, there is no any guarantee that the order will be maintained, as this is a purely compiler implementation detail, so even if it’s would be true now, for
.net 5.1(say), may be wrong.switch/caseconstruct is made for identifying unique option(s) between different available ones. So, the order does not matter, if not from performance point of view, but even there, it’s basically irrelevant, and if not, it could not be predicted for the reasons described above.So just not pay attention to this, and look on other parts of your program, if you’re looking for some performance bottlenecks.