Arraylist VS List≪≫ in C#

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.

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.

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.

ArrayList vs Listobject

You'll be able to use the LINQ extension methods directly with List<object>, but not with ArrayList, unless you inject a Cast<object>() / OfType<object> (thanks to IEnumerable<object> vs IEnumerable). That's worth quite a bit, even if you don't need type safety etc.

The speed will be about the same; structs will still be boxed, etc - so there isn't much else to tell them apart. Except that I tend to see ArrayList as "oops, somebody is writing legacy code again..." ;-p

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

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.

List vs ArrayList vs Dictionary vs Hashtable vs Stack vs Queue?

Lists

Lists allow duplicate items, can be accessed by index, and support linear traversal.

  • ArrayList - An array-based list that doesn't support generic types. It does not enforce type safety and should generally be avoided.

  • List - An array list that supports generic types and enforces type-safety. Since it is non-contiguous, it can grow in size without re-allocating memory for the entire list. This is the more commonly used list collection.

Hashes

Hashes are look-ups in which you give each item in a list a "key" which will be used to retrieve it later. Think of a hash like a table index where you can ask questions like "I'm going to find this object by this string value. Duplicate keys are not allowed.

  • HashTable - A basic key-value-pair map that functions like an indexed list.

  • Dictionary - A hashtable that supports generic types and enforces type-safety.

Queues

Queues control how items in a list are accessed. You typically push/pop records from a queue in a particular direction (from either the front or back). Not used for random access in the middle.

  • Stack - A LIFO (last in, first out) list where you push/pop records on top of each other.

  • Queue - A FIFO (first in, first out) list where you push records on top and pop them off the bottom.

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