C# | List.TrimExcess Method
Last Updated :
01 Feb, 2019
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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
List< string > mylist = new List< string >();
mylist.Add( "1" );
mylist.Add( "2" );
mylist.Add( "3" );
mylist.Add( "4" );
mylist.Add( "5" );
Console.WriteLine(mylist.Capacity);
Console.WriteLine(mylist.Count);
mylist.TrimExcess();
Console.WriteLine(mylist.Capacity);
Console.WriteLine(mylist.Count);
}
}
|
Output:
8
5
5
5
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
List< int > mylist = new List< int >();
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);
Console.WriteLine(mylist.Capacity);
Console.WriteLine(mylist.Count);
mylist.TrimExcess();
Console.WriteLine(mylist.Capacity);
Console.WriteLine(mylist.Count);
mylist.Clear();
Console.WriteLine(mylist.Capacity);
Console.WriteLine(mylist.Count);
}
}
|
Output:
16
9
9
9
9
0
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...