事件原因,之前在公司写代码的时候,带我的师傅建议我对List的长度最好在初始化的时候进行优化,这样对GC更加友好,所以就有了这个文章,来理解下List 容量自适应的实现。
List 继承于IList,IReadOnlyList
// C# 源码
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
private int _version;
[NonSerialized]
private Object _syncRoot;
static readonly T[] _emptyArray = new T[0];
// 其他内容
}
继承层次上跟JAVA差不多,继承于IList,然后在网上是ICollection
默认容量
从代码中可以看出,默认的容量是4,但是根JAVA一样,都不会立刻申请内存空间
// JAVA code
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
// 该变量初始化为
// private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// C# code
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to 16, and then increased in multiples of two as required.
public List() {
_items = _emptyArray;
}
但是很有意思,微软给出的官方的注释说容量会在第一次增加到16,然后每次都是加倍增加的。
但是看了代码,我觉得微软的这个注释可能需要更新了,这初始化的长度很明显是4啊,还写了注释告诉我是16。
[TestClass]