HashSet<T>.TrimExcess 方法

定义

重载

TrimExcess()

HashSet<T> 对象的容量设置为它包含的实际元素数,向上舍入到附近特定于实现的值。

TrimExcess(Int32)

HashSet<T> 对象的容量设置为指定数量的条目,向上舍入到附近的特定于实现的值。

TrimExcess()

Source:
HashSet.cs
Source:
HashSet.cs
Source:
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: { }
*/
let displaySet (set: HashSet<int>) =
    printf "{"

    for i in set do
        printf $" {i}"

    printfn " }"
// 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: { }
let numbers = HashSet<int>()

for i = 0 to 9 do
    numbers.Add i |> ignore

printf $"Numbers contains {numbers.Count} elements: "
displaySet numbers

numbers.Clear()
numbers.TrimExcess()

printf $"Numbers contains {numbers.Count} elements: "
displaySet numbers
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)

Source:
HashSet.cs

HashSet<T> 对象的容量设置为指定数量的条目,向上舍入到附近的特定于实现的值。

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

参数

capacity
Int32

新容量。

例外

指定的容量低于条目计数。

适用于