stalker92 stalker92 - 3 months ago 10
C# Question

List<Class>() vs List<Class>(0)

Is there any difference between executing these two lines of code:

IList<Class> list = new List<Class>();


and

IList<Class> list = new List<Class>(0);


I've been told that first, capacity-less constructor is more effective because it allocates less memory compared to constructor with 0 capacity. I've searched MSDN, and it is written there that default capacity of the List is 0 anyways and I do not see any logic in this...

Can anybody confirm or deny this theory?

Answer

You can actually answer the question pretty easily with the help of http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646

public List() {
  _items = _emptyArray;
}

vs

public List(int capacity) {
  if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
  Contract.EndContractBlock();

  if (capacity == 0)
     _items = _emptyArray;
  else
    _items = new T[capacity];
}

As you can see for yourself: If no initial capacity is supplied (ctor()) the internal _items array is set to _emptyArray, which is the same behavior for ctor(0). This looks like an internal optimization for all the ctor(0)-calls to avoid (superfluous) allocations of an empty array.

In the end, neither of the above ctor-calls is really memory-effective compared to a real initial capacity. This is the nature of the very datastructure, which dynamically extends accordingly. So, whenever you know the real capacity upfront, you should call ctor(capacity) to avoid the resizing (which is implemented here and called on every write).

Comments