C# List.ToArray performance is bad?

后端 未结 7 803
礼貌的吻别
礼貌的吻别 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:42

    This is what Microsoft's official documentation says about List.ToArray's time complexity

    The elements are copied using Array.Copy, which is an O(n) operation, where n is Count.

    Then, looking at Array.Copy, we see that it is usually not cloning the data but instead using references:

    If sourceArray and destinationArray are both reference-type arrays or are both arrays of type Object, a shallow copy is performed. A shallow copy of an Array is a new Array containing references to the same elements as the original Array. The elements themselves or anything referenced by the elements are not copied. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

    So in conclusion, this is a pretty efficient way of getting an array from a list.

提交回复
热议问题