Does key length affect dictionary performance?

I will use the dictionary in a .NET project to store a large number of objects. So I decided to use a GUID string as a key to provide unique keys for each object.

Whether a large key, such as a GUID (or even larger ones), reduces dictionary performance, for example. to retrieve an object through its key?

Thanks Andrew

+7
performance dictionary c #
source share
6 answers

I would recommend using the actual Guid rather than the string representation of Guid . Yes, when comparing strings, length affects the number of operations required, since it must compare strings by characters (at the minimum minimum, this prohibits any special options, such as IgnoreCase ). The actual Guid will give you just 16 bytes for comparison, not a minimum of 32 in string .

As the saying goes, you most likely will not notice the difference ... premature optimization and all of this. I would just go for the Guid key, as this is data.

+14
source share

The actual size of the object with respect to obtaining values ​​does not matter. The speed of finding values ​​is much more dependent on the speed of two methods in the passed instance of IEqualityComparer<T>

  • GetHashCode ()
  • Equally()

EDIT

Many people use String as an excuse to say that a larger object reduces their search performance. This must be done with salt for several reasons.

  • The performance of the above methods for String decreases performance as the size of the string increases for default comparison. Just because this is true for System.String does not mean that it is true at all
  • You could just write another IEqualityComparer<String> so that the string length is out of date.
+7
source share

Yes and no. Large lines increase the size of the dictionary memory. And larger sizes mean slightly longer times for calculating hash sizes.

But worrying about these things is probably premature optimization. Although this will be slower, this is not what you are likely to notice.

+3
source share

Apparently this is so. Here is a good test: Dictionary line test <

+1
source share

I did a quick google search and found this article.

http://dotnetperls.com/dictionary-string-key

This confirms that usually shorter keys work better than longer ones.

+1
source share

see Performance - using a Guid or Guid string object as a key for a similar question. You can check it with an alternative key.

+1
source share

All Articles