Should we initialize List(T) with size if known ?

As per documentation, it says

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.

We can decrease the capacity of a List(T) any time by calling TrimExcess method over the List(T).
If we decrease the capacity, interestingly, it is not decreased, but the memory is relocated and all the elements in the List(T) are copied into that memory location.

dafault capacity if not defined is “0”. A List doubles itself, every time the capacity limit is hit.

Capacity for the List could be checked easily, any time using List(T).Capacity property.

           List<string> animals = new List<string>();

            animals.Add("cow");
            animals.Add("bull");           

            // get List<string> capacity
            int listCapacity = animals.Capacity;
          
            // get List<string> size
            int listSize = animals.Count;

            // reduce capacity 
            animals.TrimExcess();

            // make Lis<string> empty
            animals.Clear(); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s