Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the importance of setting `IList` capacity?

Tags:

c#

.net

list

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.

like image 601
gcso Avatar asked Sep 30 '11 12:09

gcso


People also ask

What is an IList?

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.

What is List capacity?

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.

What is initial capacity of a List C#?

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.

How many items can a list hold C#?

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.


1 Answers

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.

like image 129
Justin Niessner Avatar answered Oct 02 '22 23:10

Justin Niessner