Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ ToDictionary initial capacity

I regularly use the LINQ extension method ToDictionary, but am wondering about the performance. There is no parameter to define the capacity for the dictionary and with a list of 100k items or more, this could become an issue:

IList<int> list = new List<int> { 1, 2, ... , 1000000 };
IDictionary<int, string> dictionary = list.ToDictionary<int, string>(x => x, x => x.ToString("D7"));

Does the implementation actually take the list.Count and passes it to the constructor for the dictionary? Or is the resizing of the dictionary fast enough, so I don't really have to worry about it?

like image 406
Franky Avatar asked Jul 08 '26 18:07

Franky


1 Answers

Does the implementation actually take the list.Count and passes it to the constructor for the dictionary?

No. According to ILSpy, the implementation is basically this:

Dictionary<TKey, TElement> dictionary = new Dictionary<TKey, TElement>(comparer);
foreach (TSource current in source)
{
    dictionary.Add(keySelector(current), elementSelector(current));
}
return dictionary;

If you profile your code and determine that the ToDictionary operation is your bottleneck, its trivial to make your own function based on the above code.

like image 193
akatakritos Avatar answered Jul 10 '26 06:07

akatakritos