gpt4 book ai didi

c# - 枚举 Dictionary.Values 与字典本身

转载 作者:可可西里 更新时间:2023-11-01 07:57:37 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com