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:

Get hands-on with 1400+ tech skills courses.