Size of a list list using list.Capacity

Asked

Viewed 247 times

6

Creating a list of lists:

List<List<int>> myList = new List<List<int>>();  

I add elements in myList with 1 element:

myList.Add(1);

When I do debug.writeLine(myList.capacity) me returns the value 4, my list has only 1 element.

1 answer

7


Yes, that’s right, by optimizing a list, in the current implementation, it starts with 4 elements and every time the capacity burst it doubles in size. When a list has no more capacity you need to create a new one array (there is an internal in the list) and copy all data from the array existing to the new, which is somewhat inefficient and generates pressure for the Garbage Collector, so this structure tries to minimize this already starting with a minimum value and increases more and more as it grows because if you are growing much will probably grow even more, and the bigger the copy becomes more complicated, so you should avoid more.

This occurs to avoid the call Shlemiel the Painter’s Algorithm.

Shlemiel the painter's algorithm

Yes, it will take up the space of 4 elements in the array, even if you only use one, or none, but it makes no practical difference.

Note that capacity is different from how many elements you actually have. If you want to know quantity of elements you should take the property Count, thus:

myList.Count

If you really want to create a list with an element, which I don’t recommend, you can do:

new List<List<int>>(1)

I put in the Github for future reference.

You can be 0 if you want. The ideal is to use this parameter to indicate more or less the amount you expect the list to have to avoid unnecessary allocations, then you should do the opposite, if you expect the list to have hundreds of elements, creating with size 1000 is of great value and will optimize absurdly. Even if wasting space by not using everything is usually a better solution.

  • 1

    Thanks for the explanation. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.