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) 操作です。nCount です。This method is an O(n) operation, where n is Count.

適用対象