Array versus List<T>: When to use which?

.NetArraysList

.Net Problem Overview


MyClass[] array;
List<MyClass> list;

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

.Net Solutions


Solution 1 - .Net

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.

Solution 2 - .Net

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

Solution 3 - .Net

Notwithstanding the other answers recommending List<T>, you'll want to use arrays when handling:

  • image bitmap data

  • other low-level data-structures (i.e. network protocols)

Solution 4 - .Net

Unless you are really concerned with performance, and by that I mean, "Why are you using .Net instead of C++?" you should stick with List<>. It's easier to maintain and does all the dirty work of resizing an array behind the scenes for you. (If necessary, List<> is pretty smart about choosing array sizes so it doesn't need to usually.)

Solution 5 - .Net

Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.

For example,

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.

But suppose that

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.

Solution 6 - .Net

If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.

Solution 7 - .Net

Most of the times, using a List would suffice. A List uses an internal array to handle its data, and automatically resizes the array when adding more elements to the List than its current capacity, which makes it more easy to use than an array, where you need to know the capacity beforehand.

See http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5 for more information about Lists in C# or just decompile System.Collections.Generic.List<T>.

If you need multidimensional data (for example using a matrix or in graphics programming), you would probably go with an array instead.

As always, if memory or performance is an issue, measure it! Otherwise you could be making false assumptions about the code.

Solution 8 - .Net

Arrays Vs. Lists is a classic maintainability vs. performance problem. The rule of thumb that nearly all developers follow is that you should shoot for both, but when they come in to conflict, choose maintainability over performance. The exception to that rule is when performance has already proven to be an issue. If you carry this principle in to Arrays Vs. Lists, then what you get is this:

Use strongly typed lists until you hit performance problems. If you hit a performance problem, make a decision as to whether dropping out to arrays will benefit your solution with performance more than it will be a detriment to your solution in terms of maintenance.

Solution 9 - .Net

Another situation not yet mentioned is when one will have a large number of items, each of which consists of a fixed bunch of related-but-independent variables stuck together (e.g. the coordinates of a point, or the vertices of a 3d triangle). An array of exposed-field structures will allow the its elements to be efficiently modified "in place"--something which is not possible with any other collection type. Because an array of structures holds its elements consecutively in RAM, sequential accesses to array elements can be very fast. In situations where code will need to make many sequential passes through an array, an array of structures may outperform an array or other collection of class object references by a factor of 2:1; further, the ability to update elements in place may allow an array of structures to outperform any other kind of collection of structures.

Although arrays are not resizable, it is not difficult to have code store an array reference along with the number of elements that are in use, and replace the array with a larger one as required. Alternatively, one could easily write code for a type which behaved much like a List<T> but exposed its backing store, thus allowing one to say either MyPoints.Add(nextPoint); or MyPoints.Items[23].X += 5;. Note that the latter would not necessarily throw an exception if code tried to access beyond the end of the list, but usage would otherwise be conceptually quite similar to List<T>.

Solution 10 - .Net

Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable, so follow popular convention and use a List until you have a reason not to, at which point you probably will have your reason for using an array over a List."

Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.

Solution 11 - .Net

Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.

Solution 12 - .Net

Since no one mention: In C#, an array is a list. MyClass[] and List<MyClass> both implement IList<MyClass>. (e.g. void Foo(IList<int> foo) can be called like Foo(new[] { 1, 2, 3 }) or Foo(new List<int> { 1, 2, 3 }) )

So, if you are writing a method that accepts a List<MyClass> as an argument, but uses only subset of features, you may want to declare as IList<MyClass> instead for callers' convenience.

Details:

Solution 13 - .Net

They may be unpopular, but I am a fan of Arrays in game projects.

  • Iteration speed can be important in some cases, foreach on an Array has significantly less overhead if you are not doing much per element
  • Adding and removing is not that hard with helper functions
  • Its slower, but in cases where you only build it once it may not matter
  • In most cases, less extra memory is wasted (only really significant with Arrays of structs)
  • Slightly less garbage and pointers and pointer chasing

That being said, I use List far more often than Arrays in practice, but they each have their place.

It would be nice if List where a built in type so that they could optimize out the wrapper and enumeration overhead.

Solution 14 - .Net

Populating a list is easier than an array. For arrays, you need to know the exact length of data, but for lists, data size can be any. And, you can convert a list into an array.

List<URLDTO> urls = new List<URLDTO>();

urls.Add(new URLDTO() {
	key = "wiki",
	url = "https://...",
});

urls.Add(new URLDTO()
{
	key = "url",
	url = "http://...",
});

urls.Add(new URLDTO()
{
	key = "dir",
	url = "https://...",
});

// convert a list into an array: URLDTO[]
return urls.ToArray();

Solution 15 - .Net

Keep in mind that with List is not possible to do this:

List<string> arr = new List<string>();

arr.Add("string a");
arr.Add("string b");
arr.Add("string c");
arr.Add("string d");

arr[10] = "new string";

It generates an Exception.

Instead with arrays:

string[] strArr = new string[20];

strArr[0] = "string a";
strArr[1] = "string b";
strArr[2] = "string c";
strArr[3] = "string d";

strArr[10] = "new string";

But with Arrays there is not an automatic data structure resizing. You have to manage it manually or with Array.Resize method.

A trick could be initialize a List with an empty array.

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

But in this case if you put a new element using Add method it will be injected in the end of the List.

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

arr.Add("bla bla bla"); // this will be in the end of List

Solution 16 - .Net

It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.

Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrederick The FoolView Question on Stackoverflow
Solution 1 - .NetMarc GravellView Answer on Stackoverflow
Solution 2 - .NetJon SkeetView Answer on Stackoverflow
Solution 3 - .NetAlnitakView Answer on Stackoverflow
Solution 4 - .NetSpencer RuportView Answer on Stackoverflow
Solution 5 - .NetHerman SchoenfeldView Answer on Stackoverflow
Solution 6 - .Netsmack0007View Answer on Stackoverflow
Solution 7 - .NetSune RieversView Answer on Stackoverflow
Solution 8 - .NetChristian FindlayView Answer on Stackoverflow
Solution 9 - .NetsupercatView Answer on Stackoverflow
Solution 10 - .NetmoarboilerplateView Answer on Stackoverflow
Solution 11 - .NetiliketocodeView Answer on Stackoverflow
Solution 12 - .NetsnipsnipsnipView Answer on Stackoverflow
Solution 13 - .Netuser3290232View Answer on Stackoverflow
Solution 14 - .NetBimal PoudelView Answer on Stackoverflow
Solution 15 - .NetAlberto CostaView Answer on Stackoverflow
Solution 16 - .NetsajidnizamiView Answer on Stackoverflow