枚举Dictionary.Values vs Dictionary本身

Fab*_*NET 14 .net c# dictionary .net-core asp.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();        
}
Run Code Online (Sandbox Code Playgroud)

如果字典是这样列举的,有什么区别?

foreach (var entry in _resolvedServices.Values)
{
    (entry as IDisposable)?.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

它有性能影响吗?或者是因为分配ValueCollection将消耗更多内存?

Hen*_*ema 10

你是对的,这是关于内存消耗的.差异实际上在注释中有很好的描述:访问Value一个Dictionary<TKey, TValue> ValueCollection在堆上分配a(属性类(引用类型)的属性.

foreach通过字典本身会导致调用GetEnumerator()返回一个Enumerator.这是一个struct并将分配在堆栈而不是堆上.