[英]C# Dictionary ContainsKey Vs Keys.Any()
這是我的情況:
我正在使用字典對象存儲一些鍵,然后基於對象中存在的鍵,代碼正在執行某些操作。
到現在dictionaryObject.Any(x => x.Key.Equals("SomeParameter"))
我一直在使用dictionaryObject.Any(x => x.Key.Equals("SomeParameter"))
- Any()
dictionaryObject.Any(x => x.Key.Equals("SomeParameter"))
。 直到我的字典對象突然獲得200,000個鍵之前,這都是可行的並且滿足所有情況。
它開始影響性能,其余過程也是如此。
然后我意識到,有一個字典方法ContainsKey("SomeParameter")
,使用它之后,性能確實得到了改善。
現在,我更感興趣的是查看ContainsKey
與LINQ Any
什么不同,因為我加下划線的代碼分別for
& foreach
,這意味着它foreach
列表。
這是ContainsKey方法的代碼
private int FindEntry(TKey key)
{
if ((object) key == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
if (this.buckets != null)
{
int num = this.comparer.GetHashCode(key) & int.MaxValue;
for (int index = this.buckets[num % this.buckets.Length]; index >= 0; index = this.entries[index].next)
{
if (this.entries[index].hashCode == num && this.comparer.Equals(this.entries[index].key, key))
return index;
}
}
return -1;
}
如您所見,一旦有了鑰匙,
它是O(1)運算,而Any
是IEnumerable
的一部分,並且對元素序列執行簡單的迭代,直到滿足條件為止,因此O(n)-可調用性大大降低。 這就是您觀察到的-隨着數據量的增長, Any
性能會變差。
請參閱mscorlib中System.Collections.Generic的Dictionary
聲明
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>, //this one "brings" Any
IEnumerable,
IDictionary,
ICollection,
IReadOnlyDictionary<TKey, TValue>,
IReadOnlyCollection<KeyValuePair<TKey, TValue>>,
ISerializable,
IDeserializationCallback
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.