簡體   English   中英

C#字典ContainsKey與Keys.Any()

[英]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什么不同,因為我加下划線的代碼分別forforeach ,這意味着它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)運算,而AnyIEnumerable的一部分,並且對元素序列執行簡單的迭代,直到滿足條件為止,因此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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM