Lookups with Switch Expressions
03/30/2024
In a recent PR I have optimized parsing known header values, such CacheControlHeaderValue
or MediaTypeHeaderValue
.
The original code used a Dictionary<>
to look up a Func<string, T?>
parsing method, with a string input and a generic type T
return type. In this blog post I will summarize the pros and cons of different alternatives that were considered as part of the optimization.
FrozenDictionary
This dictionary contains known Func<string, T?>
parsers. These known parsers do not change at runtime. Using a FrozenDictionary would bring performance benefits for the lookup operations. However, freezing the dictionary itself takes time at runtime, because when freezing the new dictionary builds an efficient lookup. This is usually worth the trade-off as freezing only needs to happen once during the lifetime of the application. However, in this case all the contents of this dictionary are known at compile time.