Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of looking up .NET Dictionary value by key?

I have a dictionary of 10000 Product/Colour/Size combinations which I have created with something like:

AllRecords = DB.ProductColourSizes _
             .ToDictionary(function(b) String.Format("{0}_{1}_{2}", _
             b.ProductCode, b.ColourCode, b.SizeCode))

So an example key is like "13AI_GRS_M"

I have to sync up my database with the company's ERP every 30 minutes, and for every Colour/Size combo I need to use this dictionary to add, edit or delete records. I wish they supplied ID numbers.

I don't know how Dictionary works internally. How quick is .NET at finding the right value based on such a key? Should I sort the database query, or does .NET have some other way of identifying the key?

Or should I convert it into a List and use a Dictionary to identify the right index? Or another way completely?

I also use Static Dictionaries in this way all over website's application, so learning a better way of doing this would have quite an influence.

Many thanks, Steve

like image 459
Steve McGill Avatar asked Aug 19 '10 12:08

Steve McGill


2 Answers

For what you're doing the dictionary is perfect.

The retrieval time on keys for items in a dictionary is damn fast, but ultimately relies on the hash code function of the key (in your case string.GetHashCode()).

You're in luck, because the .Net string's GetHashCode() function is very good. If you do get a hash code clash, .Net will call the Equals method on the object, and so guarantees uniqueness.

We have dictionaries with hundreds of thousands of items, and the lookup times are negligible.

Sorting the result-set from the database will be of no benefit in this case.

Hope this helps.

like image 87
Binary Worrier Avatar answered Sep 30 '22 14:09

Binary Worrier


How quick is .NET at finding the right value based on such a key?

The complexity of retrieving a value for a key is close to O(1) according to MSDN, so it's pretty fast...

Also from MSDN:

The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

If you use a string as the key, you should be OK, since we can probably assume that the String class uses an efficient hashing algorithm...

like image 42
Thomas Levesque Avatar answered Sep 30 '22 15:09

Thomas Levesque