开发者

Does the length of key affect Dictionary performance?

开发者 https://www.devze.com 2022-12-08 15:29 出处:网络
I will use a Dictionary in a .NET project to store a large number of objects. Therefore I decided to use a GUID-string as a key, to ensure unique keys for 开发者_运维问答each object.

I will use a Dictionary in a .NET project to store a large number of objects. Therefore I decided to use a GUID-string as a key, to ensure unique keys for 开发者_运维问答each object.

Does a large key such as a GUID (or even larger ones) decrease the performance of a Dictionary, e.g. for retrieving an object via its key?

Thanks, Andrej


I would recommend using an actual Guid rather than the string representation of the Guid. Yes, when comparing strings the length does affect the number of operations required, since it has to compare the strings character-by-character (at a bare minimum; this is barring any special options like IgnoreCase). The actual Guid will give you only 16 bytes to compare rather than the minimum of 32 in the string.

That being said, you are very likely not going to notice any difference...premature optimization and all that. I would simply go for the Guid key since that's what the data is.


The actual size of an object with respect to retrieving values is irrelevant. The speed of lookup of values is much more dependent on the speed of two methods on the passed in IEqualityComparer<T> instance

  • GetHashcode()
  • Equals()

EDIT

A lot of people are using String as a justification for saying that larger object size decreases lookup performance. This must be taken with a grain of salt for several reasons.

  • The performance of the above said methods for String decrease in performance as the size of the string increases for the default comparer. Just because it's true for System.String does not mean it is true in general
  • You could just as easily write a different IEqualityComparer<String> in such a way that string length was irrelevant.


Yes and no. Larger strings increase the memory size of a dictionary. And larger sizes mean slightly longer times to calculate hash sizes.

But worrying about those things is probably premature optimization. While it will be slower, it's not anything that you will probably actually notice.


Apparently it does. Here is a good test: Dictionary String Key Test


I did a quick Google search and found this article.

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

It confirms that generally shorter keys perform better than longer ones.


see Performance - using Guid object or Guid string as Key for a similar question. You could test it out with an alternative key.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号