HashSet<T>.TrimExcess 方法
定义
将 HashSet<T> 对象的容量设置为它包含的实际元素数,向上舍入为接近的特定于实现的值。Sets the capacity of a HashSet<T> object to the actual number of elements it contains, rounded up to a nearby, implementation-specific value.
public:
void TrimExcess();
public void TrimExcess ();
member this.TrimExcess : unit -> unit
Public Sub TrimExcess ()
示例
下面的示例创建并填充 HashSet<T> 集合,然后清除集合,然后释放它所引用的内存。The following example creates and populates a HashSet<T> collection, and then clears the collection and releases the memory referenced by it.
HashSet<int> Numbers = new HashSet<int>();
for (int i = 0; i < 10; i++)
{
Numbers.Add(i);
}
Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);
Numbers.Clear();
Numbers.TrimExcess();
Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);
void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
/* This example produces output similar to the following:
* Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 }
* Numbers contains 0 elements: { }
*/
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim Numbers As HashSet(Of Integer) = New HashSet(Of Integer)()
For i As Integer = 0 To 9
Numbers.Add(i)
Next i
Console.Write("Numbers contains {0} elements: ", Numbers.Count)
DisplaySet(Numbers)
Numbers.Clear()
Numbers.TrimExcess()
Console.Write("Numbers contains {0} elements: ", Numbers.Count)
DisplaySet(Numbers)
End Sub
' This code example produces output similar to the following:
' Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 }
' Numbers contains 0 elements: { }
Private Shared Sub DisplaySet(ByVal coll As HashSet(Of Integer))
Console.Write("{")
For Each i As Integer In coll
Console.Write(" {0}", i)
Next i
Console.WriteLine(" }")
End Sub
End Class
注解
TrimExcess HashSet<T> 已知不会添加新元素时,可以使用方法将对象的内存开销降到最低。You can use the TrimExcess method to minimize a HashSet<T> object's memory overhead once it is known that no new elements will be added. 若要完全清除 HashSet<T> 对象并释放它所引用的所有内存,请在调用方法后调用此方法 Clear 。To completely clear a HashSet<T> object and release all memory referenced by it, call this method after calling the Clear method.
此方法是 O (n) 操作,其中 n 是 Count 。This method is an O(n) operation, where n is Count.