数组与列表<T>:何时使用哪个?

Array versus Listlt;Tgt;: When to use which?(数组与列表lt;Tgt;:何时使用哪个?)
本文介绍了数组与列表<T>:何时使用哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但这绝对是个例外;对于一般的业务线处理,List<T> 每次都会获胜.

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

这篇关于数组与列表&lt;T&gt;:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)