集合初始化是否正确设置了 HashSet 的初始大小?

Does a collection initialize set the initial size of a HashSet properly?

集合初始化是否也设置结果集的初始大小?

具体来说:这段代码...

var someSet = new HashSet<int> { 42, 667 };

...等同于下面的代码,其中明确设置了初始大小?

var someSet = new HashSet<int>(2) { 42, 667 };

TL;DR; 如果您有一个预先存在的数组或集合,请不要使用集合初始值设定项。

集合初始化器仅使用 Add() 来创建集合,所以是的,先设置大小会提高性能。不过,在大多数情况下,您实际上不太可能注意到任何差异。


the relevant HashSet constructor 的代码有这个 gem:

        public HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
        {
...........
               // to avoid excess resizes, first set size based on collection's count. Collection
                // may contain duplicates, so call TrimExcess if resulting hashset is larger than
                // threshold
                ICollection<T> coll = collection as ICollection<T>;
                int suggestedCapacity = coll == null ? 0 : coll.Count;
                Initialize(suggestedCapacity);
 
                this.UnionWith(collection);

因此,如果您有一个现有数组(ICollection<T>List<T> 也是),那么这无关紧要。只有在使用 LINQ Where 等或使用集合初始值设定项时才会出现问题。