源代码ConcurrentDictionary
提到了使用的可能性TAlternateKey
,这是一个 ref 结构。https
://github.com/dotnet/runtime/blob/main/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs
另外,经过一番搜索,我还发现了其他有趣的例子。例如: https ://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs
#if NET9_0_OR_GREATER
private readonly ConcurrentDictionary<string, CacheEntry>.AlternateLookup<ReadOnlySpan<char>> _stringAltLookup;
public CoherentState()
{
_stringAltLookup = _stringEntries.GetAlternateLookup<ReadOnlySpan<char>>();
}
#endif
//...
#if NET9_0_OR_GREATER
internal bool TryGetValue(ReadOnlySpan<char> key, [NotNullWhen(true)] out CacheEntry? entry)
=> _stringAltLookup.TryGetValue(key, out entry);
#endif
#if NET9_0_OR_GREATER
private readonly ConcurrentDictionary<string, CacheEntry>.AlternateLookup<ReadOnlySpan<char>> _stringAltLookup;
public CoherentState()
{
_stringAltLookup = _stringEntries.GetAlternateLookup<ReadOnlySpan<char>>();
}
#endif
为了获得更好的性能,我是否应该使用ReadOnlySpan<char>
作为 Key,而ConcurrentDictionary
不是string
?