Understanding Collection Choices
Understand different .NET collection types including lists, dictionaries, stacks, queues, and sets. Explore their characteristics, use cases, and methods to improve performance by managing capacity effectively.
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:
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 ...