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

Posted by Neil N on Stack Overflow See other posts from Stack Overflow or by Neil N
Published on 2010-05-03T20:18:31Z Indexed on 2010/05/03 20:28 UTC
Read the original article Hit count: 244

Certain collection types in .Net have an optional "Initial Capacity" constructor param. i.e.

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 the capacity grows like it does for a StringBuiler, which doubles each time the capacity is hit, and each re-allocation is costly, why not pre-set 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 allocated RAM is allocated for nothing.

Please spare me the "premature optimization" speil for the O(n^n)th time. I know it won't make my apps any faster or save any meaningful amount of memory, this is mostly out of curiosity.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET