C# When Should I Use List and When Should I Use Arraylist

c# When should I use List and when should I use arraylist?

The main time to use ArrayList is in .NET 1.1

Other than that, List<T> all the way (for your local T)...

For those (rare) cases where you don't know the type up-front (and can't use generics), even List<object> is more helpful than ArrayList (IMO).

ArrayList vs List in C#

Yes, pretty much. List<T> is a generic class. It supports storing values of a specific type without casting to or from object (which would have incurred boxing/unboxing overhead when T is a value type in the ArrayList case). ArrayList simply stores object references. As a generic collection, List<T> implements the generic IEnumerable<T> interface and can be used easily in LINQ (without requiring any Cast or OfType call).

ArrayList belongs to the days that C# didn't have generics. It's deprecated in favor of List<T>. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.

Which is better? array, ArrayList or ListT (in terms of performance and speed)

List<T> should generally be preferred over ArrayList

  • faster for value types as it avoids boxing.
  • strongly typed elements

If you want lists you expose to callers to be immutable, this is supported by both List<T> and ArrayList:

List<T>.AsReadOnly()
ArrayList.ReadOnly(ArrayList list);

Your question asks about choosing between ArrayList and List<T>, but your example shows an array, which is neither.

When to use ArrayList over array[] in c#?

Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array.

ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayLists fall short because you could pass in an ArrayList containing any type. ArrayLists use a dynamically expanding array internally, so there is also a hit to expand the size of the internal array when it hits its capacity.

What you really want to use is a generic list like List<T>. This has all the advantages of Array and ArrayLists. It is strongly typed and it supports a variable length of items.

Array versus ListT: When to use which?

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

What is the difference between an Array, ArrayList and a List?

They are different object types. They have different capabilities and store their data in different ways.

An Array (System.Array) is fixed in size once it is allocated. You can't add items to it or remove items from it. Also, all the elements must be the same type. As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance. Also, System.Array supports multiple dimensions (i.e. it has a Rank property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).

An ArrayList is a flexible array which contains a list of objects. You can add and remove items from it and it automatically deals with allocating space. If you store value types in it, they are boxed and unboxed, which can be a bit inefficient. Also, it is not type-safe.

A List<> leverages generics; it is essentially a type-safe version of ArrayList. This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it'll generate a compile-time error.

C# is there ever a reason to use ArrayList instead of ListT anymore?

As you said, if for some reason you are stuck with .Net 1.1 then you don't have a choice.

Your question seems to indicate that there is a choice. So then there is no reason to userArrayList. Anything that ArrayList can do, List<T> can do as well, if not better.

When will one prefer array, LinkedList or ArrayList over ListT?

LinkedList

Here is a list of differentiators from the List implementation. You use it when the items in the list need to maintain a specific order (hence the next and previous references).

Represents a doubly linked list.

LinkedList<T> provides separate nodes of type LinkedListNode<T>, so insert and removal are O(1) operations.

You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional objects allocated on the heap. Because the list also maintains an internal count, getting the Count property is an O(1) operation.

Each node in a LinkedList<T> object is of the type LinkedListNode<T>. Because the LinkedList<T> is doubly linked, each node points forward to the Next node and backward to the Previous node.

List Vs ArrayList

ArrayList is a deprecated implementation used in the past. Prefer List<T> generic implementation in any new code.

As a generic collection, List<T> implements the generic IEnumerable<T> interface and can be used easily in LINQ

ArrayList belongs to the days that C# didn't have generics. It's deprecated in favor of List<T>. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.

Array vs List

Array is a fixed size collection and it supports multiple dimensions. It is the most efficient of the three for simple insert and iterations.

Is an ArrayList an Array or a List?

ArrayList behaves like a list (in particular, its count of elements can grow, unlike an array), but it's backed by an array, which will be dynamically resized as needed. Hence the name ArrayList.

Things that behave like lists don't have to be backed by arrays (they could be linked lists, for example), but ArrayList is.

When should I use a List vs a LinkedList

Edit

Please read the comments to this answer. People claim I did not do
proper tests. I agree this should not be an accepted answer. As I was
learning I did some tests and felt like sharing them.

Original answer...

I found interesting results:

// Temporary class to show the example
class Temp
{
public decimal A, B, C, D;

public Temp(decimal a, decimal b, decimal c, decimal d)
{
A = a; B = b; C = c; D = d;
}
}

Linked list (3.9 seconds)

        LinkedList<Temp> list = new LinkedList<Temp>();

for (var i = 0; i < 12345678; i++)
{
var a = new Temp(i, i, i, i);
list.AddLast(a);
}

decimal sum = 0;
foreach (var item in list)
sum += item.A;

List (2.4 seconds)

        List<Temp> list = new List<Temp>(); // 2.4 seconds

for (var i = 0; i < 12345678; i++)
{
var a = new Temp(i, i, i, i);
list.Add(a);
}

decimal sum = 0;
foreach (var item in list)
sum += item.A;

Even if you only access data essentially it is much slower!! I say never use a linkedList.




Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list)

Linked List (51 seconds)

        LinkedList<Temp> list = new LinkedList<Temp>();

for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);

list.AddLast(a);
var curNode = list.First;

for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it
curNode = curNode.Next;

list.AddAfter(curNode, a); // Insert it after
}

decimal sum = 0;
foreach (var item in list)
sum += item.A;

List (7.26 seconds)

        List<Temp> list = new List<Temp>();

for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);

list.Insert(i / 2, a);
}

decimal sum = 0;
foreach (var item in list)
sum += item.A;

Linked List having reference of location where to insert (.04 seconds)

        list.AddLast(new Temp(1,1,1,1));
var referenceNode = list.First;

for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);

list.AddLast(a);
list.AddBefore(referenceNode, a);
}

decimal sum = 0;
foreach (var item in list)
sum += item.A;

So only if you plan on inserting several items and you also somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time.



Related Topics



Leave a reply



Submit