What is the importance of setting a lists capacity at creation?
For example, say I know for sure that my list will only contain n items throughout its lifetime.
Save Article. In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.
Capacity is the number of elements that the List<T> can store before resizing is required, whereas Count is the number of elements that are actually in the List<T>. Capacity is always greater than or equal to Count.
The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain. The default capacity is 4. If 5 elements are there, then its capacity is doubled and would be 8.
List size can be increased up to 2 billion (only when your system works on 64-bit or higher) to store large List<T> objects.
Inside of a List<T>
, there is a statically sized collection that holds your items. Once you reach the capacity of that collection, the List<T>
re-sizing it which is a performance hit (may or may not be significant to you).
By setting the initial capacity, you are avoiding having to perform those re-sizing operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With