MyClass[] array;
List<MyClass> list;

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

推荐答案

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

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.

See also:

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

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

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

.net相关问答推荐

NuGet 兼容与计算框架(Xamarin 和 .NET 6)

Msbuild try 构建 msbuild.exe 而不是我的 .csproj 文件

.NET MAUI 的登录页面

如何知道变量是否只是指向另一个对象的pointer或者它是否可以独立存在

如何将 Javascript 日期时间转换为 C# 日期时间?

在 ASP.NET MVC 中我可以在哪里放置自定义类?

如何创建 LINQ to SQL 事务?

如何在没有抽象基类的情况下强制覆盖后代中的方法?

从 Web.Config 中的邮箱友好显示名称存储 Smtp

如何从字符串中删除所有字母字符?

C# 的 Actors 有什么好的实现吗?

日期时间是什么意思?在 C# 中是什么意思?

Mono 是树莓派

为什么 .NET 中不需要 Maven?

.net 自定义配置如何不区分大小写解析枚举 ConfigurationProperty

ObservableCollection<> 与 List<>

解密 .NET clr20r3 异常参数 P1..P10

析构函数、dispose 和 finalize 方法的区别

在 .NET 中计算目录大小的最佳方法是什么?

DataContractSerializer vs XmlSerializer:每个序列化器的优缺点