Array 与 List<T>:何时使用哪个? [英] Array versus List<T>: When to use which?
问题描述
MyClass[] array;
List<MyClass> list;
一种优于另一种的情况是什么?为什么?
What are the scenarios when one is preferable over the other? And why?
推荐答案
实际上,您很少会想要使用数组.任何时候你想添加/删除数据时,一定要使用 List
,因为调整数组大小很昂贵.如果您知道数据是固定长度的,并且您想出于某些非常具体的原因(在基准测试之后)进行微优化,那么数组可能很有用.
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.
List
比数组提供了很多的功能(尽管 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
作为计数器——List
是一维的;其中 - 因为您有矩形(等)数组,例如 int[,]
或 string[,,]
- 但是还有其他方法可以对此类数据进行建模(如果需要)) 在对象模型中.
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.
另见:
也就是说,我在protobuf-中大量使用数组net 项目;完全为了性能:
That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:
- 它做了很多位移,所以
byte[]
对于编码非常重要; - 我使用本地滚动
byte[]
缓冲区,在向下发送到底层流(和 v.v.)之前填充该缓冲区;比BufferedStream
等快; - 它在内部使用基于数组的对象模型(
Foo[]
而不是List
),因为大小一旦构建就固定了,并且需要要非常快.
- 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 thanBufferedStream
etc; - it internally uses an array-based model of objects (
Foo[]
rather thanList<Foo>
), since the size is fixed once built, and needs to be very fast.
但这绝对是个例外;对于一般业务线处理,List
每次都会获胜.
But this is definitely an exception; for general line-of-business processing, a List<T>
wins every time.
这篇关于Array 与 List<T>:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!