C#列表< T> .ToArray表现不好? [英] C# List<T>.ToArray performance is bad?

查看:260
本文介绍了C#列表< T> .ToArray表现不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.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.

这篇关于C#列表&LT; T&GT; .ToArray表现不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆