List
句法:
public void TrimExcess ();
笔记:
- 如果没有新元素添加到集合中,则可以使用此方法来最小化集合的内存开销。
- 要将List
重置为其初始状态,请在调用TrimExcess方法之前调用Clear方法。 - 修剪空的List
会将List 的容量设置为默认容量。 - 但是,重新分配和复制大型List
的成本可能很高,因此,如果列表的容量超过90%,则TrimExcess方法将不执行任何操作。这样避免了以相对较小的收益而产生较大的重新分配成本。 - 此方法是O(n)运算,其中n是Count。
下面的程序说明了List
范例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 mylist = new List();
// 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);
}
}
输出:
8
5
5
5
范例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 mylist = new List();
// 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);
}
}
输出:
16
9
9
9
9
0
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.trimexcess?view=netframework-4.7.2