【问题标题】:Is there a difference between new List<T>() and new List<T>(0)new List<T>() 和 new List<T>(0) 有区别吗
【发布时间】:2015-06-16 21:54:59
【问题描述】:

new List&lt;T&gt;()new List&lt;T&gt;(0) 有区别吗?

这可能是一个微优化,但其想法是了解内存分配方面的差异。

【问题讨论】:

标签: c# .net list memory-management


【解决方案1】:

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。代码(就内存占用而言)是相同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2017-05-08
    相关资源
    最近更新 更多