Should a .NET generic dictionary be initialised with a capacity equal to the number of items it will contain?

前端 未结 6 1910
小鲜肉
小鲜肉 2020-12-17 17:12

If I have, say, 100 items that\'ll be stored in a dictionary, should I initialise it thus?

var myDictionary = new Dictionary(100);
<         


        
6条回答
  •  [愿得一人]
    2020-12-17 17:18

    Specifying the initial capacity to the Dictionary constructor increases performance because there will be fewer number of resizes to the internal structures that store the dictionary values during ADD operations.

    Considering that you specify a initial capacity of k to the Dictionary constructor then:

    1. The Dictionary will reserve the amount of memory necessary to store k elements;
    2. QUERY performance against the dictionary is not affected and it will not be faster or slower;
    3. ADD operations will not require more memory allocations (perhaps expensive) and thus will be faster.

    From MSDN:

    The capacity of a Dictionary(TKey, TValue) is the number of elements that can be added to the Dictionary(TKey, TValue) before resizing is necessary. As elements are added to a Dictionary(TKey, TValue), the capacity is automatically increased as required by reallocating the internal array.

    If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary(TKey, TValue).

提交回复
热议问题