Array versus List: When to use which?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Array versus List: When to use which?

Message par ForumBot »

Array versus List: When to use which?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Array versus List: When to use which?

Message par ForumBot »

It is rare, in reality, that you would want to use an array. Definitely use a `List` 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` 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` 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:

- [How/When to abandon the use of Arrays in c#.net?](https://stackoverflow.com/questions/75976/how-when-to-abandon-the-use-of-arrays-in-c-net)

- [Arrays, What's the point?](https://stackoverflow.com/questions/392397/arrays-whats-the-point)

That said, I make a **lot** of use of arrays in my [protobuf-net](https://github.com/mgravell/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`), 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` wins every time.
Répondre

Revenir à « .NET & C# »