C# | List.TrimExcess Method
List<T>.TrimExcess Method is used to set the capacity to the actual number of elements in the List<T>, if that number is less than a threshold value.
Syntax:
public void TrimExcess ();
Note:
- This method can be used to minimize a collection’s memory overhead if no new elements will be added to the collection.
- To reset a List<T> to its initial state, call the Clear method before calling TrimExcess method.
- Trimming an empty List<T> sets the capacity of the List<T> to the default capacity.
- The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain.
- This method is an O(n) operation, where n is Count.
Below programs illustrate the use of List<T>.TrimExcess Method:
Example 1:
// C# code to set the capacity to the // actual number of elements in the List using System; using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of strings List< string > mylist = new List< string >(); // Inserting elements into List mylist.Add( "1" ); mylist.Add( "2" ); mylist.Add( "3" ); mylist.Add( "4" ); mylist.Add( "5" ); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); } } |
chevron_right
filter_none
Output:
8 5 5 5
Example 2:
// C# code to set the capacity to the // actual number of elements in the List using System; using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of integers List< int > mylist = new List< int >(); // Inserting elements into List mylist.Add(45); mylist.Add(78); mylist.Add(32); mylist.Add(231); mylist.Add(123); mylist.Add(76); mylist.Add(726); mylist.Add(716); mylist.Add(876); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using clear method mylist.Clear(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); } } |
chevron_right
filter_none
Output:
16 9 9 9 9 0
Reference: