问题描述
MyClass[] array;
List<MyClass> list;
在哪些情况下一种优于另一种?为什么?
What are the scenarios when one is preferable over the other? And why?
推荐答案
实际上,您很少会想要使用数组.任何时候你想添加/删除数据时,一定要使用 List<T>
,因为调整数组大小很昂贵.如果您知道数据是固定长度的,并且您想出于某些非常具体的原因(在基准测试之后)进行微优化,那么数组可能会很有用.
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<T>
提供了比数组更多的功能很多(尽管 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<T>
是一维的;where-因为您有矩形(等)数组,例如 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.
另见:
- 如何/何时放弃使用c#.net 中的数组?
- 数组,有什么意义?
也就是说,我在 protobuf- 中大量使用了数组净项目;完全是为了性能:
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<T>
每次都会获胜.
But this is definitely an exception; for general line-of-business processing, a List<T>
wins every time.
这篇关于数组与列表<T>:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!