0

I want to make a dictionary the key type of which is string and the type of values is list. I think I could make one like this:

static Dictionary<string, List<String>> dic_list = new Dictionary<string, List<String>>();

There will be a lot of append(Add) calls to each list(more than a million per list and there are dozens of lists). I don't know exactly how many strings will be added, but I know their size (200 bytes per each). I wonder if knowing the size can be advantageous to the performance. Is it better to set a dictionary this way in this scenario?:

static Dictionary<string, List<String>> dic_list = new Dictionary<string, List<String>>(200);

I'd appreciate it if you could share any ways to optimize this kind of jobs.

I referred to this thread: Performance of Arrays vs. Lists

maynull
  • 1,936
  • 4
  • 26
  • 46
  • 1
    *I wonder if knowing the size can be advantageous to the performance* maybe, why don't you benchmark it? There is possibly **some** performance increase, is it worth it, will depend. – Liam Apr 30 '19 at 14:43
  • That being said, if the dictionary is going to contain several dozens of entries, there will not be a noticeable performance difference. The number of elements in those contained lists does not matter at all. – GSerg Apr 30 '19 at 14:45
  • the dotnetperl site does a lot of benchmarking of this type [Dictionary optimization](https://www.dotnetperls.com/dictionary-optimization) or see the dictionnary section on general optimization page [here](https://www.dotnetperls.com/optimization) – valerian Havaux Apr 30 '19 at 14:45
  • 3
    Note that the "initial capacity" given to Dictionary and List is the *number of elements*, not the total size of elements. Strings and lists are both reference types, and as such are heap-allocated. Your List therefore just contains a number of references (which are all the same size), and it does not care about the sizes of your individual strings. – canton7 Apr 30 '19 at 14:45
  • it would be quicker to know the size of the value list than the dictionary itself. if you won't be going over 200, the difference will hardly be noticeable. If you could have `Dictionary dict = new Dictionary();` would be your fastest solution. – Icculus018 Apr 30 '19 at 14:47
  • As others have said, do not worry about dictionary efficiency. The dictionary just points a key to one of a few dozen lists -- absolutely trivial. What WILL matter is how efficient those lists will be. – Slothario Apr 30 '19 at 15:54

0 Answers0