Next in our series on the API changes for .NET 6, we look at collections.
List, Stack, and Queue Capacity
Before performing a large set of inserts into a Dictionary or HashSet, it is helpful to call EnsureCapacity
with the expected collection size. This allows the collection to perform one resize operation upfront, avoiding the possibility of multiple resizes being needed.
The EnsureCapacity method has been added to the List<T>
, Stack<T>
, and Queue<T>
classes so they too can gain the performance benefit.
A notable exclusion from this group is Collection. Unlike the others, Collection<T>
may optionally wrap another collection which may not necessarily expose an EnsureCapacity method. As a subclass of Collection<T>
, ObservableCollection<T>
cannot expose an EnsureCapacity
method either.
This isn’t the only design flaw in Collection<T>
and ObservableCollection<T>
. The lack of an AddRange
method has long annoyed developers. It also lacks the high performance, struct based IEnumerator
that List<T>
offers. So perhaps it’s time to offer a new alternative that doesn’t have the IList<T>
wrapping constructor and its associated problems.
#development #dotnet #dotnet 6