Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary Performance

I am using a Dictionary to store data, and will be caching it. I would like to avoid server memory issues, and have good performance by limiting the size of the Dictionary<>, either in size or number of entries.
What is the best method of doing this? Is there another class I should be considering other than a Dictionary?

like image 359
derek Avatar asked Apr 30 '10 13:04

derek


2 Answers

You don't need to limit the size of the Dictionary to archieve good performance.

As the documentation says:

Retrieving a value by using its key is very fast, close to O(1)

like image 100
Foxfire Avatar answered Oct 04 '22 23:10

Foxfire


There are several other classes you can select from like

  • SortedDictionary
  • List
  • HashSet

you can review the options by looking at System.Collections.Generic Namespace.

Their is a very good post, describibg pros and cons for all most of the collection classes at MSDN

  • Selecting a Collection Class

If you are not satisfied by what these classes are provide, you can go for your own collection class or design a custom Dictionary your self.

you will need to inherit your custom dictionary fron IDictionary Interface and other classes / interfaces or may write all from scratch.

Here is the signature for Dictionary class at MSDN

[SerializableAttribute]
[ComVisibleAttribute(false)]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>,
    IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable,
    ISerializable, IDeserializationCallback
like image 22
Asad Avatar answered Oct 04 '22 21:10

Asad