What is the default capacity of a List?

As an .net developer we use List very frequently. List represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Most of us think framework development team would have made all the List operations optimal. We never try to put thought, if we can do some thing to make it better. We can do few things as a developer to help .net framework to use List  optimally. One of those things is setting its capacity when we create a list. if you know in advance how many items you are going to add in a list, then it will be a better to make a list of predefined capacity.

if we don’t define a capacity of a list then it starts with a Capacity of 0. When you add the first element, then .net framework allocates a capacity of 4. After that, the capacity keeps doubling if expansion is needed.

This code spinet should demonstrate the behavior:

List<int> list = new List<int>();
int capacity = list.Capacity;
Console.WriteLine("Capacity: " + capacity);

for (int i = 0; i < 100000; i++)
    if (list.Capacity > capacity)
        capacity = list.Capacity;
        Console.WriteLine("Capacity: " + capacity);

Capacity should be used if you know roughly how many items you want to store in List (or in Stack, or Queue).

That way you will avoid memory copying. The memory copying happens because under the hood Lists (Stacks and Queues) rely on array to store their items. That array size is you capacity, but it’s not the same as the list size. As size of list needs to be bigger than the size of array, the List implementation will allocate a bigger array and will copy all items from old array to the new one plus newly added items.

So, if you know that you may have from, say, 50 to 60 items in your list, create a list with capacity 60 and no memory deallocation will happen. And Garbage Collector will not have to clean up old arrays

What is the default capacity of a List?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s