C#列表< T> .ToArray表现不好?不好、列表、GT、LT

2023-09-03 10:15:35 作者:荼蘼花開

我使用.net 3.5(C#),我听说过C#的性能名单,其中,T> .ToArray 是坏的,因为它的内存拷贝所有元素,以形成一个新的数组。是真的吗?

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

推荐答案

没有事实并非如此。性能还是不错的,因为它是所有内存拷贝所有的元素(*),形成一个新的数组。

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.

修改

在回答您的意见,使用反射是检查的实施(见下文)的好方法。或者只是想了你将如何实现它,并把它的信任,微软的工程师也不会拿出一个更糟糕的解决方案,几分钟的时间。

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").

编辑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.