C# | Setting the capacity to the actual number of elements in a SortedList object
SortedList.TrimToSize Method is used to set the capacity to the actual number of elements in a SortedList object.
public virtual void TrimToSize ();
Below programs illustrate the use of above-discussed method:
Before trimming the capacity is: 16 After trimming the capacity is: 6
Before Using TrimToSize Method: Count: 5 Capacity: 16 Values are: Geeks! Hello Noida to Welcome After Using TrimToSize Method: Count: 5 Capacity: 5 Values are: Geeks! Hello Noida to Welcome After Using Clear Method: Count: 0 Capacity: 5 Values are: After Again Using TrimToSize Method: Count: 0 Capacity: 0 Values are:
- The main use of this method is that it can be used to minimize a collection’s memory overhead if no new elements will be added to the collection.
- To reset a SortedList object to its initial state, call the Clear method before calling TrimToSize. Trimming an empty SortedList set the capacity of the SortedList to the default capacity.
- This method is an O(n) operation, where n is Count.