Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary Add/Set in one call for performance reasons

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?

like image 622
Dirk Boer Avatar asked Oct 18 '22 13:10

Dirk Boer


1 Answers

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.

like image 82
Timothy Shields Avatar answered Oct 21 '22 04:10

Timothy Shields