MyClass[] array; List<MyClass> list;
What are the scenarios when one is preferable over the other? And why?
Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.
Data Types Storage: Array can store elements of only one data type but List can store the elements of different data types too. Hence, Array stores homogeneous data values, and the list can store heterogeneous data values.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one. List over arrays.
An array is faster than a list in python since all the elements stored in an array are homogeneous i.e., they have the same data type whereas a list contains heterogeneous elements. Moreover, Python arrays are implemented in C which makes it a lot faster than lists that are built-in in Python itself.
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:
byte[]
is pretty much essential for encoding;byte[]
buffer which I fill before sending down to the underlying stream (and v.v.); quicker than BufferedStream
etc;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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With