C # predefined list

I work in C # and I create a list (newList) that I can get from the length of another list (otherList). In C #, the list is implemented in such a way that preallocating the length of the list is better for performance using otherList.Count or just use newList.Add (obj) and not worry about the length?

+4
source share
4 answers

The following constructor for List<T>is implemented to improve performance in scripts like yours:

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

public List(int capacity)

Just pass the container in the constructor.

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

+7
source

, - - .

, List<T> . , , .

+4

"" MSDN

List<T> - , List<T> . List<T>, .

, List<T>.

, TrimExcess Capacity . List<T>.

, , , , . , , , .

, , .

+4

. :

var repetitions = 100000000
var list = new List<object>();
for (var i = 0; i < repetitions; i++)
    list.Add(new object());

, . :

  • : 6561, 6394, 6556, 6283, 6466
  • : 5951, 6037, 5885, 6044, 5996
  • : 6710, 6665, 6729, 6760, 6624

? , ( ).

, , .

Please note that in terms of memory, accurate pre-allocation is the most efficient in terms of memory, as the lack of pre-allocation will increase your list to the minimum required capacity.

0
source

All Articles