Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preallocating List c#

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?

like image 497
ford prefect Avatar asked Oct 07 '13 16:10

ford prefect


People also ask

Is memory preallocated in linked list?

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.

What does it mean to preallocate an array?

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.

What does Preallocating mean in Matlab?

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 ...

Should I preallocate array Python?

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.


2 Answers

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);

like image 69
Trevor Elliott Avatar answered Sep 18 '22 11:09

Trevor Elliott


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.

like image 42
Daniel Hilgarth Avatar answered Sep 20 '22 11:09

Daniel Hilgarth