In a Dictionary<struct,int>
: is it possible to Add/Set in one call?
So is it possible to do the code below in only one lookup per entry?
_KeyToPoints = new Dictionary<Key,int>();
foreach ( var entry in billionEntries )
{
int originalValue;
// first lookup
_KeyToPoints.TryGetValue(entry.Key, out originalValue);
// second lookup
_KeyToPoints[key] = originalValue + points;
}
This is done in a very tight loop over a huge amount of data, so all performance matters.
Or is there a better suitable data structure?
Yes, there is a way to do this, but it has a downside. Consider this class:
class Ref<T>
{
public T Value;
}
You can use a Dictionary<K, Ref<int>> dict
and then do this:
Ref<int> count;
if (!dict.TryGetValue(key, out count))
{
count = new Ref<int> { Value = 0 };
dict[key] = count;
}
count.Value += points;
The downside is that now you have an additional heap object per entry in your dictionary. Depending on your situation, this may or may not be acceptable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With