Understanding Collection Choices
Learn about common collection types, their implementations, and when to use each type.
Improving performance by ensuring the capacity of a collection
Since .NET 1.1, types like StringBuilder
have had a method named EnsureCapacity
that can pre-size its internal storage array to the expected final size of the string. This improves performance because it does not have to repeatedly increment the array size as more characters are appended. Since .NET Core 2.1, types like Dictionary
and HashSet
have also had EnsureCapacity
. In .NET 6 and later, collections like List
, Queue
, and Stack
now have an EnsureCapacity
method too, as shown in the following code:
List<string> names = new();names.EnsureCapacity(10_000);// load ten thousand names into the list
There are several different choices of collections that we can use for different purposes: lists, dictionaries, stacks, queues, sets, and many other, more specialized collections.
Lists
Lists, that is, a type that implements IList
, are ordered collections, as shown in the following code:
namespace System.Collections.Generic;[DefaultMember("Item")] // also known as this indexerpublic interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable{T this[int index] { get; set; }int IndexOf(T item);void Insert(int index, T item);void RemoveAt(int index);}
IList
derives from ICollection
so it has the ...