C# List.ToArray performance is bad?

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

    No that's not true. Performance is good since all it does is memory copy all elements (*) to form a new array.

    Of course it depends on what you define as "good" or "bad" performance.

    (*) references for reference types, values for value types.

    EDIT

    In response to your comment, using Reflector is a good way to check the implementation (see below). Or just think for a couple of minutes about how you would implement it, and take it on trust that Microsoft's engineers won't come up with a worse solution.

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

    Of course, "good" or "bad" performance only has a meaning relative to some alternative. If in your specific case, there is an alternative technique to achieve your goal that is measurably faster, then you can consider performance to be "bad". If there is no such alternative, then performance is "good" (or "good enough").

    EDIT 2

    In response to the comment: "No re-construction of objects?" :

    No reconstruction for reference types. For value types the values are copied, which could loosely be described as reconstruction.

提交回复
热议问题