- Frugal Cafe
- Posts
- FC40: SmallFrozenDictionary could be slower
FC40: SmallFrozenDictionary could be slower
Linear search without using hash code
There is a recent discussion about the merit of FrozenDictionary, so I looked into its implementation.
FrozenDictionary is an abstract class with lots of implementations, optimized for different geometries. SmallFrozenDictionary is one of them. Its source code can be found here: runtime/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/SmallFrozenDictionary.cs at main · dotnet/runtime (github.com)
Here is the TryGetValue implementation:
Normal dictionary lookup is 1 GetHashCode call for hash code miss, add 1 Equals call for cache hit, unless there are hash duplications.
For SmallFrozenDictionary, there could be up to N Equals calls. The maximum number of elements allowed in SmallFrozenDictionary is 4.
So SmallFrozenDictionary lookup could be slower than normal dictionary, when Equals check is complex enough. It could even be much slower.
But SmallFrozenDictionary is definitely a memory (working set) optimization.