Recently I asked a question on SO that had mentioned the possible use of an c# ArrayList for a solution. A comment was made that using an arraylist is bad. I would like to more about this. I have never heard this statement before about arraylists. could sombody bring me up to speed on the possible performance problems with using arraylists

c#. .net-2


Solution 1:

The main problem with ArrayList is that is uses object - it means you have to cast to and from whatever you are encapsulating. It is a remnant of the days before generics and is probably around for backwards compatibility only.

You do not have the type safety with ArrayList that you have with a generic list. The performance issue is in the need to cast objects back to the original (or have implicit boxing happen).

Implicit boxing will happen whenever you use a value type - it will be boxed when put into the ArrayList and unboxed when referenced.

The issue is not just that of performance, but also of readablity and correctness. Since generics came in, this object has become obsolete and would only be needed in .NET 1.0/1.1 code.

Solution 2:

If you're storing a value type (int, float, double, etc - or any struct), ArrayList will cause boxing on every storage and unboxing on every element access. This can be a significant hit to performance.

In addition, there is a complete lack of type safety with ArrayList. Since everything is stored as "object", there's an extra burden on you, as a developer, to keep it safe.

In addition, if you want the behavior of storing objects, you can always use List<object>. There is no disadvantage to this over ArrayList, and it has one large (IMO) advantage: It makes your intent (storing an untyped object) clear from the start.

ArrayList really only exists, and should only be used, for .NET 1.1 code. There really is no reason to use it in .NET 2+.

Solution 3:

ArrayList is not a generic type so it must store all items you place in it as objects. This is bad for two reasons. First, when putting value types in the ArrayList you force the compiler to box the value type into a reference type which can be costly. Second, you now have to cast everything you pull out of the array list. This is bad since you now need to make sure you know what objects are in there.

List avoids these issues since it is constructed with the proper type. For example:

List<int> ints =  new List<int>();
ints.Add(5); //no boxing
int num = ints[0]; // no casting