Preallocating List c#

The following constructor for List<T> is implemented for the purpose of improving performance in scenarios like yours:

http://msdn.microsoft.com/en-us/library/dw8e0z9z.aspx

public List(int capacity)

Just pass the capacity in the constructor.

newList = new List<string>(otherList.Count);


If you know the exact length of the new list, creating it with that capacity indeed performs - a bit - better.

The reason is that the implementation of List<T> internally uses an array. If this gets too small, a new array is created and the items from the old array are copied over to the new item.


Taken from the Remarks section on MSDN

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

The capacity can be decreased by calling the TrimExcess method or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the List<T>.

So, this would suggest that there would be a performance increase if you have an estimate of the size of the list you are going to populate. Of course the other-side of this is allocating a list size too big and therefore using up memory unnecessarily.

To be honest, I would not worry about this sort of micro optimization unless I really need to.