简体   繁体   中英

C# Dictionary ContainsKey Vs Keys.Any()

Here is my situation:

I am using dictionary object to store some keys, and then based on key exists in the object, code is performing some action.

Till now I was using - LINQ - Any() dictionaryObject.Any(x => x.Key.Equals("SomeParameter")) . This was working will and satisfying all scenarios till my dictionary object suddenly got 200,000 keys.

It started impacting on performance, and so does rest of process.

Then I realize, there is a dictionary method ContainsKey("SomeParameter") , and after using this, performance really improved.

Now I am more interested to see what ContainsKey does different than LINQ Any as I underlined code uses for & foreach respectively, which means it loops thru the list.

This is a code for ContainsKey method

  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;
    }

As you might see, once you have a key,

  • you get hash code for it
  • access bucket to get index
  • access data with that index

It's O(1) operations, while Any is a part of IEnumerable , and performs simple iteration over a sequence of elements, until condition is met, hence O(n) - much less scallable. And that's what you observe - with amount of data that grows, performance becomes worse for Any .

See declaration of Dictionary from System.Collections.Generic, mscorlib

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM