Adding Complex Keys in the Dictionary! Does it effect the performance

I am just writing a program that requires Dictionary as (in C#.net-4.5)

 Dictionary<List<Button>, String> Label_Group = new Dictionary<List<Button>, String>();

my friend suggests to use key as string, does this makes any difference in performance while doing the search!,

I am just curious how it work

Jon Skeet
people
quotationmark

In fact, the lookup based on a List<Button> will be faster than based on a string, because List<T> doesn't override Equals. Your keys will just be compared by reference effectively - which is blazingly cheap.

Compare that with using a string as a key:

  • The hash code needs to be computed, which is non-trivial
  • Each string comparison performs an equality check, which has a short cut for equal references (and probably different lengths), but will otherwise need to compare each character until it finds a difference or reaches the end

(Taking the hash code of an object of a type which doesn't override GetHashCode may require allocation of a SyncBlock - I think it used to. That may be more expensive than hashing very short strings...)

It's rarely a good idea to use a collection as a dictionary key though - and if you need anything other than reference equality for key comparisons, you'll need to write your own IEqualityComparer<>.

people

See more on this question at Stackoverflow