Alex Rivera | Logout

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

Asked 2010-05-03T20:18:31.123
55

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

Dictionary<string, string> something = new Dictionary<string, string>(20);

List<string> anything = new List<string>(50);

I can't seem to find what the default initial capacity is for these objects on MSDN.

If I know I will only be storing 12 or so items in a dictionary, doesn't it make sense to set the initial capacity to something like 20?

My reasoning is, assuming that the capacity grows like it does for a StringBuilder, which doubles each time the capacity is hit, and each reallocation is costly, why not preset the size to something you know will hold your data, with some extra room just in case? If the initial capacity is 100, and I know I will only need a dozen or so, it seems as though the rest of that memory is allocated for nothing.

Edit
Report

1 Answer

13

If you know the size, then tell it; a minor optimisation in most "small" cases, but useful for bigger collections. I would mainly worry about this if I am throwing a "decent" amount of data in, as it can then avoid having to allocate, copy and collect multiple arrays.

Most collections indeed use a doubling strategy.

answered 2010-05-03T20:22:14.963

Your Answer