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:
How/When to abandon the use of Arrays in c#.net?
Arrays, What's the point?
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
But this is definitely an exception; for general line-of-business processing, a List<T>
wins every time.
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.
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)
List<T>
here rather than a byte array?
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.)
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.
To
is going to create an object that has no ability to modify the original instance, as opposed to strChars as char[]
which if valid would suggest you're now able to modify the original object.
str
internally uses an array and ToCharArray
returns a reference to this array then the client can mutate str
by changing the elements of that array, even if the size remains fixed. Yet you write 'It is clear that modification of "strChars" will not mutate the original "str" object'. What am I missing here? From what I can see, in either case the client may have access to the internal representation and, regardless of the type, this would allow mutation of some kind.
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
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.
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.
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>
.
Point[] arr;
, it's possible for code to say, e.g. arr[3].x+=q;
. Using e.g. List<Point> list
, it would be necessary to instead say Point temp=list[3]; temp.x+=q; list[3]=temp;
. It would be helpful if List<T>
had a method Update<TP>(int index, ActionByRefRef<T,TP> proc, ref TP params)
. and compilers could turn list[3].x+=q;
into {list.Update(3, (ref int value, ref int param)=>value+=param, ref q);
but no such feature exists.
list[0].X += 3;
will add 3 to the X property of the first element of the list. And list
is a List<Point>
and Point
is a class with X and Y properties
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.
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.
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:
Why array implements IList?
How do arrays in C# partially implement IList
List
, it only implements the IList
interface.
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.
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();
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
new List<T>(int)
constructor.
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.
IEnumerable<T>
- then I can stream objects rather than buffer them.
Success story sharing