-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Opening this issue at the suggestion of @tannergooding .
One scenario when working with enums is to map from a string to the corresponding enum value.
If the string input is coming from an external source (for instance, as part of a web request) it may be necessary to do this conversion in a case-insensitive way.
The most natural code to write to accomplish this is generally Enum.TryParse, passing the flag to do a case-insensitive parse:
TestEnum? GetEnumValue(string value)
=> Enum.TryParse(value, ignoreCase: true, out TestEnum result) ? result : nullHowever, benchmarking (in this case, using the .NET 10 preview SDK) shows this approach is very expensive compared to other approaches, such as performing a dictionary lookup:
Benchmark results are from:
https://github.com/Treit/MiscBenchmarks/tree/main/StringSwitchVsDictionary
It would be very useful if Enum.TryParse could be optimized so that the most natural way of writing this kind of code does not come with a significant performance penalty.