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

前端 未结 6 1922
小鲜肉
小鲜肉 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:31

    I did a quick test, probably not scientific, but if I set the size it took 1.2207780 seconds to add one million items and it took 1.5024960 seconds to add if I didn't give the Dictionary a size... this seems negligible to me.

    Here is my test code, maybe someone can do a more rigorous test but I doubt it matters.

    static void Main(string[] args)
            {
                DateTime start1 = DateTime.Now;
                var dict1 = new Dictionary(1000000);
    
                for (int i = 0; i < 1000000; i++)
                    dict1.Add(i.ToString(), i.ToString());
    
                DateTime stop1 = DateTime.Now;
    
                DateTime start2 = DateTime.Now;
                var dict2 = new Dictionary();
    
                for (int i = 0; i < 1000000; i++)
                    dict2.Add(i.ToString(), i.ToString());
    
                DateTime stop2 = DateTime.Now;
    
                Console.WriteLine("Time with size initialized: " + (stop1.Subtract(start1)) + "\nTime without size initialized: " + (stop2.Subtract(start2)));
                Console.ReadLine();
            }
    

提交回复
热议问题