HashSet扩容机制在时间和空间上的浪费，远大于你的想象

二：HashSet的扩容机制

1. 如何查看

public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int num = (int)Math.Sqrt(candidate);
for (int i = 3; i <= num; i += 2)
{
if (candidate % i == 0)
{
return false;
}
}
return true;
}
return candidate == 2;
}

private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int num = (_items.Length == 0) ? 4 : (_items.Length * 2);
}
}

2. HashSet 二次扩容探究

public static int ExpandPrime(int oldSize)
{
int num = 2 * oldSize;
if ((uint)num > 2146435069u && 2146435069 > oldSize)
{
return 2146435069;
}
return GetPrime(num);
}

2. 您嗅出风险了吗？

时间上的风险

public static readonly int[] primes = new int[72]
{
2009191,
2411033,
2893249,
3471899,
4166287,
4999559,
5999471,
7199369
};

static void Main(string[] args)
{
var hashSet = new HashSet(Enumerable.Range(0, 2893249));

}

0:000> !clrstack -l

000000B8F4DBE500 00007ffaf00132ae ConsoleApplication3.Program.Main(System.String[]) [C:\4\ConsoleApp1\ConsoleApp1\Program.cs @ 16]
LOCALS:
0x000000B8F4DBE538 = 0x0000020e0b8fcc08
0:000> !DumpObj /d 0000020e0b8fcc08
Name:        System.Collections.Generic.HashSet1[[System.Int32, System.Private.CoreLib]]
Size:        64(0x40) bytes
File:        C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.0-preview.5.20278.1\System.Collections.dll
Fields:
MT    Field   Offset                 Type VT     Attr            Value Name
00007ffaf0096d10  4000017        8       System.Int32[]  0 instance 0000020e2025e9f8 _buckets
00007ffaf00f7ad0  4000018       10 ...ivate.CoreLib]][]  0 instance 0000020e2bea1020 _slots
00007ffaeffdf828  4000019       28         System.Int32  1 instance          2893250 _count
0:000> !DumpObj /d 0000020e2025e9f8
Name:        System.Int32[]
Size:        23997908(0x16e2dd4) bytes
Array:       Rank 1, Number of elements 5999471, Type Int32 (Print Array)
Fields:
None

空间上的风险

static void Main(string[] args)
{
var hashSet1 = new HashSet(Enumerable.Range(0, 2893249));

var hashSet2 = new HashSet(Enumerable.Range(0, 2893249));

}

0:000> !clrstack -l
000000B1B4FEE460 00007ffaf00032ea ConsoleApplication3.Program.Main(System.String[]) [C:\4\ConsoleApp1\ConsoleApp1\Program.cs @ 18]
LOCALS:
0x000000B1B4FEE4B8 = 0x000001d13363cc08
0x000000B1B4FEE4B0 = 0x000001d13363d648

0:000> !objsize 0x000001d13363cc08
sizeof(000001D13363CC08) = 46292104 (0x2c25c88) bytes (System.Collections.Generic.HashSet1[[System.Int32, System.Private.CoreLib]])
0:000> !objsize 0x000001d13363d648
sizeof(000001D13363D648) = 95991656 (0x5b8b768) bytes (System.Collections.Generic.HashSet1[[System.Int32, System.Private.CoreLib]])

static void Main(string[] args)
{
var hashSet2 = new HashSet(Enumerable.Range(0, 2893249));
}

0:011> !dumpheap -stat
00007ffaf84f7ad0        3    123455868 System.Collections.Generic.HashSet1+Slot[[System.Int32, System.Private.CoreLib]][]

0:011> !DumpHeap /d -mt 00007ffaf84f7ad0

0:011> !gcroot 0000016c91308048
Found 0 unique roots (run '!gcroot -all' to see all roots).
0:011> !gcroot 0000016c928524b0
Found 0 unique roots (run '!gcroot -all' to see all roots).
0:011> !gcroot 0000016ce9e61020
0000006AFAB7E5F0 00007FFAF84132AE ConsoleApplication3.Program.Main(System.String[]) [C:\4\ConsoleApp1\ConsoleApp1\Program.cs @ 15]
rbp-18: 0000006afab7e618
->  0000016C8000CC08 System.Collections.Generic.HashSet1[[System.Int32, System.Private.CoreLib]]
->  0000016CE9E61020 System.Collections.Generic.HashSet1+Slot[[System.Int32, System.Private.CoreLib]][]

0:011> !do 0000016c91308048
Name:        System.Collections.Generic.HashSet1+Slot[[System.Int32, System.Private.CoreLib]][]
Size:        16743180(0xff7b0c) bytes
Array:       Rank 1, Number of elements 1395263, Type VALUETYPE (Print Array)
Fields:
None

0:011> !do 0000016c928524b0
Name:        System.Collections.Generic.HashSet1+Slot[[System.Int32, System.Private.CoreLib]][]
Size:        34719012(0x211c524) bytes
Array:       Rank 1, Number of elements 2893249, Type VALUETYPE (Print Array)
Fields:
None

0:011> !do 0000016ce9e61020
Name:        System.Collections.Generic.HashSet1+Slot[[System.Int32, System.Private.CoreLib]][]
Size:        71993676(0x44a894c) bytes
Array:       Rank 1, Number of elements 5999471, Type VALUETYPE (Print Array)
Fields:
None

3. 有解决方案吗？

public void TrimExcess()
{
int prime = HashHelpers.GetPrime(m_count);
Slot[] array = new Slot[prime];
int[] array2 = new int[prime];
int num = 0;
for (int i = 0; i = 0)
{
array[num] = m_slots[i];
int num2 = array[num].hashCode % prime;
array[num].next = array2[num2] - 1;
array2[num2] = num + 1;
num++;
}
}
}

三： 总结

HashSet的时间和空间上虚占远比你想象的大很多，而且实占也不小，因为底层用到了双数组 m_slotsm_buckets ，每个Slot还有三个元素: struct Slot { int hashCode;internal int next;internal T value; }` ，所以了解完原理之后谨慎着用吧。