HashSet<T>.TrimExcess 方法

定義

多載

TrimExcess()

HashSet<T> 物件的容量設定為所包含之項目的實際數目,已四捨五入為鄰近的實作特定值。

TrimExcess(Int32)

TrimExcess()

來源:
HashSet.cs
來源:
HashSet.cs
來源:
HashSet.cs

HashSet<T> 物件的容量設定為所包含之項目的實際數目,已四捨五入為鄰近的實作特定值。

public:
 void TrimExcess();
public void TrimExcess ();
member this.TrimExcess : unit -> unit
Public Sub TrimExcess ()

範例

下列範例會建立並填入 HashSet<T> 集合,然後清除集合並釋放它所參考的記憶體。

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> 。 若要完全清除 HashSet<T> 物件並釋放它所參考的所有記憶體,請在呼叫 Clear 方法之後呼叫此方法。

這個方法是 O (n) 作業,其中 nCount

適用於

TrimExcess(Int32)

來源:
HashSet.cs
public:
 void TrimExcess(int capacity);
public void TrimExcess (int capacity);
member this.TrimExcess : int -> unit
Public Sub TrimExcess (capacity As Integer)

參數

capacity
Int32

適用於