new List<T>()
之间有区别吗?和 new List<T>(0)
?
可能这是一个微优化,但目的是理解内存分配方面的差异。
最佳答案
Here is the actual source code (为简洁起见,对某些部分进行了删减)
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];
}
如您所见,调用 List()
和 List(0)
都只是将 _emptyArray
分配给 _items
.代码(就内存占用而言)是相同的。
关于c# - new List<T>() 和 new List<T>(0) 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878950/