作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 GitHub 上探索 ASP.NET 核心的资源,看看 ASP.NET 团队使用了什么样的技巧来加速框架。我看到了让我感兴趣的东西。在 ServiceProvider 的源代码中,在 Dispose 实现中,他们枚举了一个字典,并添加了注释以指示性能技巧:
private readonly Dictionary<IService, object> _resolvedServices = new Dictionary<IService, object>();
// Code removed for brevity
public void Dispose()
{
// Code removed for brevity
// PERF: We've enumerating the dictionary so that we don't allocate to enumerate.
// .Values allocates a KeyCollection on the heap, enumerating the dictionary allocates
// a struct enumerator
foreach (var entry in _resolvedServices)
{
(entry.Value as IDisposable)?.Dispose();
}
_resolvedServices.Clear();
}
字典这样枚举有什么区别?
foreach (var entry in _resolvedServices.Values)
{
(entry as IDisposable)?.Dispose();
}
它对性能有影响吗?或者是因为分配了一个 ValueCollection会消耗更多内存吗?
最佳答案
没错,这是关于内存消耗的。差异实际上在评论中得到了很好的描述:accessing the Value
Dictionary<TKey, TValue>
的属性will allocate a ValueCollection
,这是堆上的一个类(引用类型)。
foreach
'通过字典本身导致调用 GetEnumerator()
返回 Enumerator
.这是 struct
并将分配在堆栈上而不是堆上。
关于c# - 枚举 Dictionary.Values 与字典本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658991/
我是一名优秀的程序员,十分优秀!