Reputation: 16256
Before flagging this as a duplicate please double check.
I'm accumulating some stats in dictionary.
Dictionary<string, int> stats;
When an event happens I update stats
:
if (!stats.ContainsKey(eventName))
stats.Add(eventName, eventValue);
else
stats[eventName] = stats[eventName] + eventValue;
The problem is this code does 2 lookups for the first occurrence of an event and 3 lookups otherwise. The first occurrence is not a big deal. But those 3 lookups for updating are really bad. How could I improve this?
Upvotes: 1
Views: 111
Reputation: 1500185
You can fetch the value when you check for containment. In fact, in this case you can make it unconditional:
int value;
stats.TryGetValue(eventName, out value);
stats[eventName] = value + eventValue;
This uses the fact that value
will be 0 if there's no entry for eventName
. You could make it explicit if you want:
int value;
if (!stats.TryGetValue(eventName, out value))
{
stats.Add(eventName, eventValue);
}
else
{
stats[eventName] = value + eventValue;
}
Either way, you're now down to one fetch and one set.
Alternatively, you could use ConcurrentDictionary
and its AddOrUpdate
method.
Upvotes: 4