I have a Dictionary<string, decimal> with a fixed number of entries, and I want to update many of its values frequently, but only for keys that already exist. If a key is not already in the dictionary, I don't want to add it, because my goal is to restrict the dictionary to a fixed size. So the code below (using the set indexer) will not work for my needs:
dictionary[key] = newValue;
This code will update the value of the key if it's already there, or it will insert a new key/value pair if it's not. That's not what I want. So I wrote an extension method TryUpdate for the Dictionary<TKey, TValue> class, with the desirable behavior:
public static bool TryUpdate<TKey, TValue>(
this Dictionary<TKey, TValue> source,
TKey key, TValue value)
{
ArgumentNullException.ThrowIfNull(source);
if (!source.ContainsKey(key))
return false;
source[key] = value;
return true;
}
Now my code works as expected:
dictionary.TryUpdate(key, newValue);
What I don't like to the above implementation is that if the key already exists, which is the common case in my scenario, the key will be hashed twice in each TryUpdate operation. So in order to get the guarantee that my dictionary will not grow beyond its initial size, I am going to pay a doubled price in terms of performance. The keys are long strings, so the hashing cost is significant. Is there any way to rewrite my TryUpdate method, so that it is as performant as the set indexer?