C# List.ToArray performance is bad?

后端 未结 7 809
礼貌的吻别
礼貌的吻别 2020-12-14 01:22

I\'m using .Net 3.5 (C#) and I\'ve heard the performance of C# List.ToArray is \"bad\", since it memory copies for all elements to form a new array. Is

7条回答
  •  青春惊慌失措
    2020-12-14 01:31

    For any kind of List/ICollection where it knows the length, it can allocate an array of exactly the right size from the start.

    T[] destinationArray = new T[this._size];
    Array.Copy(this._items, 0, destinationArray, 0, this._size);
    return destinationArray;
    

    If your source type is IEnumerable (not a List/Collection) then the source is:

    items = new TElement[4];
    ..
    if (no more space) {
        TElement[] newItems = new TElement[checked(count * 2)];
        Array.Copy(items, 0, newItems, 0, count);
        items = newItems;
    

    It starts at size 4 and grows exponentially, doubling each time it runs out of space. Each time it doubles, it has to reallocate memory and copy the data over.

    If we know the source-data size, we can avoid this slight overhead. However in most cases eg array size <=1024, it will execute so quickly, that we don't even need to think about this implementation detail.

    References: Enumerable.cs, List.cs (F12ing into them), Joe's answer

提交回复
热议问题