Parsing string to enum with digit as first char takes a very long time (original) (raw)
Note: This has to do with mscorlib. https://github.com/Microsoft/referencesource sent me here, but this doesn't look like the place where this is handled. Am I right?
When parsing strings to enums with TryParse, in some cases this takes way longer than in all the other cases. After a bit of research I found that all the strings with a digit as first char are slower. This is due to the attempt to parse the string to the underlying type (https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/enum.cs#L441) with a Convert.ChangeType, which can throw an exception, because further down the line it uses (for example) Int32.Parse instead of TryParse (https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/convert.cs#L1121).
The time it takes to create the Exception is significant. In my project I ended up writing a new Enum parser to circumvent this issue.
"Something": 240.49 ns per parse
"1Somethin": 37178.57 ns per parse
"123456789": 485.63 ns per parse
As users expect Convert.ToXxx() to throw an exception when it fails, changing this is a bad idea I think. Possible solutions I can think of:
- Extend the Convert class with Try-methods that don't throw exceptions, and use those while trying to parse an enum (much work)
- Instead of checking whether the first character is a digit (https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/enum.cs#L434), change that line to a TryParse of the whole string (the easier way)