Icerman
Icerman

Reputation: 1119

C# Generic List with default size or supply one

I am wondering if there is difference (in the aspect of performance, memory saving) to define a list with a default size or specify one.

List<object> m_objects = new List<object>();

or 

List<object> m_objects = new List<object>(100);

Both will increase the size by doubling up if more items are added, right?

Thanks,

Upvotes: 4

Views: 3550

Answers (4)

Nicholas Carey
Nicholas Carey

Reputation: 74287

List<T> is, under the covers, an array. Its initial size looks to be 4 elements. When that is exceeded, the underlying array is reallocated with twice the size. So if you know the likely maximum size of the list, you're better off specifying it as you'll avoid relatively expensive allocations and copying.

Upvotes: 1

c0deNinja
c0deNinja

Reputation: 3986

If your list is less than 100,000 in size, the performance is the same in milliseconds!

But if your list is larger than say 1,000,000 the second way will be faster.

Upvotes: 0

becike
becike

Reputation: 365

The capacity of a list start with 0 if you not specify in the constructor, and it's increasing when necessarily (first to 4 then always double the previous value).

        var list = new List<object>();
        int capacity = list.Capacity;
        Console.WriteLine("Initial capacity: {0}", list.Capacity);
        for (int i = 0; i < 10000; i++)
        {
            list.Add(new object());
            if (list.Capacity > capacity)
            {
                capacity = list.Capacity;

                Console.WriteLine("Capacity is {0} when count is {1}", list.Capacity, list.Count);
            }

Upvotes: 1

SLaks
SLaks

Reputation: 887509

If you know that you will have more than 100 items, the second one is faster.

Every time it "doubles up", it needs to copy the contents of the entire existing array. For large lists, this can be slow.
If you specify the capacity, it won't need to resize at all until it gets bigger than what you specified.

If you never add more than 100 items, it justs wastes a bit of memory (specifically, IntPtr.Size * (Capacity - Count))

Upvotes: 8

Related Questions