I am working in c# and I am creating a list (newList) that I can get from the length of another list (otherList). In c# is list implemented in a way that preallocating the length of the list is better for performance using otherList.Count or to just use newList.Add(obj) and not worry about the length?
An array needs to be pre-allocated before use and is limited by its storage capacity. A linked-list is created and its nodes are allocated memory during the run time. The usage of linked-list results in efficient usage of memory as the nodes that form the list are allocated dynamically.
Pre-allocating Space Thus, if you know (or have a good guess) at how big the array needs to be in the first place, you can "pre-allocate" it, meaning pre-size the array.
Preallocating a Nondouble MatrixWhen you preallocate a block of memory to hold a matrix of some type other than double , avoid using the method. A = int8(zeros(100)); This statement preallocates a 100-by-100 matrix of int8 , first by creating a full matrix of double values, and then by converting each element to int8 ...
You don't need to preallocate anything. Behind the scenes, the list type will periodically allocate more space than it needs for its immediate use to amortize the cost of resizing the underlying array across multiple updates.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With