数组与列表< T>:当要使用哪个?数组、要使、列表、LT

2023-09-02 01:16:33 作者:心暖与我安

MyClass[] array;
List<MyClass> list;

什么情况下,当一个是preferable比其他?为什么?

What are the scenarios when one is preferable over the other? And why?

推荐答案

这是罕见的,在现实中,你可能需要使用一个数组。绝对使用名单,其中,T&GT; 要添加/删除数据,因为调整阵列是昂贵的任何时候。如果您知道数据的长度是固定的,你要微优化某些非常特殊原因(基准之后),则阵列可能是有用的。

It is rare, in reality, that you would want to use an array. Definitely use a List<T> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.

名单,其中,T&GT; 提供的很多的不是一个数组更多的功能(尽管LINQ找齐了位),并且几乎总是正确的选择。除了 PARAMS当然参数。 ;-p

List<T> offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except for params arguments, of course. ;-p

作为反 - 名单,其中,T&GT; 是一维的;在这里,你必须有矩形(等)阵列像 INT [,] 字符串[,,] - 但有一个对象模型建模这样的数据(如果需要)的其他方式。

As a counter - List<T> is one-dimensional; where-as you have have rectangular (etc) arrays like int[,] or string[,,] - but there are other ways of modelling such data (if you need) in an object model.

另请参阅:

How/When放弃使用数组在C#.NET? 阵列,有什么意义呢? How/When to abandon the use of Arrays in c#.net? Arrays, What's the point?

不过,我利用阵列的一个很多在我的的protobuf -net 项目;完全是为了表现:

That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:

在它做了很多位移的,所以字节[] 是pretty的编码多的基础; 在我使用本地滚动字节[] 缓冲区,我送​​下到底层流(和VV)前填写;比 BufferedStream 快捷等; 在内部使用对象的数组为基础的模式(富[] ,而不是名单,其中,富&GT; )中,由于大小是固定一旦建成,并且需要非常快。 it does a lot of bit-shifting, so a byte[] is pretty much essential for encoding; I use a local rolling byte[] buffer which I fill before sending down to the underlying stream (and v.v.); quicker than BufferedStream etc; it internally uses an array-based model of objects (Foo[] rather than List<Foo>), since the size is fixed once built, and needs to be very fast.

但是,这绝对是个例外;对于业务线的一般处理,一个名单,其中,T&GT; 胜每次

But this is definitely an exception; for general line-of-business processing, a List<T> wins every time.