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

标签 c# .net dictionary asp.net-core .net-core

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

相关文章:

c# - EF Code First 中的多对多关系表示

c# - 为什么在 C# 中允许 "long"作为数组长度?

c# - 如何从 Process.start() 获取 processID

c# - 固定对象时的 GC 行为

c++ - 检查 map c++中是否存在元素

iphone - 使用 MKOverlay 的 pointCounts 错误

c# - 事件处理程序覆盖?

c# - 如何自动注册Web服务器控件所需的HttpHandler?

.net - 使用 system.windows.forms.webbrowser 进行 Windows 身份验证

swift - (应该很简单)添加到 Swift 字典