Initial capacity of collection types, e.g. Dictionary, List

前端 未结 4 886
春和景丽
春和景丽 2020-11-29 05:56

Certain collection types in .Net have an optional \"Initial Capacity\" constructor parameter. For example:

Dictionary something = new          


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 06:25

    Another issue with the ConcurrentDictionary (currently) and using its constructor to set an initial size is that its performance appears to be hindered.

    For example, here's some example code and benchmarks I tried.

    I ran the code on my machine and got similar results.

    That is, when the initial size is specified, it does nothing to increase the ConcurrentDictionary's speed when adding objects. Technically, I think it should because it doesn't have to take time or resources to resize itself.

    Yes, it may not run as fast as a normal Dictionary, but I would still expect a ConcurrentDictionary with its initial size set to have consistent, faster performance than a ConcurrentDictionary that doesn't have its initial size set, especially when one knows in advance the number of items that are going to be added to it.

    So the moral of the story is setting the initial size doesn't always guarantee a performance improvement.

提交回复
热议问题