Dir*_*oer 5 c# performance dictionary
在一个Dictionary<struct,int>:是否可以在一个电话中添加/设置?
那么每个条目只能进行一次查找,可以执行下面的代码吗?
_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;
}
Run Code Online (Sandbox Code Playgroud)
这是在大量数据的非常紧密的循环中完成的,因此所有性能都很重要.
或者是否有更合适的数据结构?
是的,有一种方法可以做到这一点,但它有一个缺点。考虑这个类:
class Ref<T>
{
public T Value;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 aDictionary<K, Ref<int>> dict然后执行以下操作:
Ref<int> count;
if (!dict.TryGetValue(key, out count))
{
count = new Ref<int> { Value = 0 };
dict[key] = count;
}
count.Value += points;
Run Code Online (Sandbox Code Playgroud)
缺点是现在字典中的每个条目都有一个额外的堆对象。根据您的情况,这可能会也可能不会被接受。
| 归档时间: |
|
| 查看次数: |
575 次 |
| 最近记录: |