C# Dictionary Performance

前端 未结 5 1663
死守一世寂寞
死守一世寂寞 2021-01-05 20:01

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&

相关标签:
5条回答
  • 2021-01-05 20:40

    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
    
    0 讨论(0)
  • 2021-01-05 20:45

    One thing to keep in mind is that when you initialize a Dictionary you can set the initial capacity. If you know how big your list will be, set it to the correct size and you won't have any "wasted" space. If you don't specify the capacity, it will set a default starting capacity and resize/grow as needed, which takes a performance hit.

    0 讨论(0)
  • 2021-01-05 20:51

    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)

    0 讨论(0)
  • 2021-01-05 20:54

    "A cache without an expiration policy is just a memory leak."

    (Sorry, unattributed as I don't know who first said it.)

    0 讨论(0)
  • 2021-01-05 20:55

    You will need to create your own class inheriting from the Dictionary class. Override the Add and set Item methods to limit the number of entries as objects are added.

    0 讨论(0)
提交回复
热议问题