Is there any difference between new List <T> () and new List <T> (0)

Is there a difference between new List<T>()

and new List<T>(0)

?

Maybe it's micro-optimization, but the idea is to understand the difference in the timing of memory allocation .

+3


source to share


1 answer


Here is the actual source code (some parts are truncated for brevity)

    static readonly T[]  _emptyArray = new T[0];  

    public List() {
        _items = _emptyArray;
    }

    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 calls List()

and List(0)

, just assign _emptyArray

to _items

. The code (in terms of memory size) is identical.

+10


source







All Articles