Skip to content

Case-insensitive Enum.TryParse is very slow compared to alternative approaches #118548

@Treit

Description

@Treit

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 : null

However, 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:

Image

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions