views:

103

answers:

2

which one is more memory efficient?
which one works faster with 1000000 items?
is there anything better?

+12  A: 

A List<T> is generally preferable to using an ArrayList because it is a type safe collection. This means that you get build time type safety. It is also more memory efficient for value types because entries in an ArrayList will be boxed because its a list of type object:

eg: Adding an integer to a List<int> will put the data on the heap using an int[] as the underlying data structure. Adding an integer to an ArrayList will put the data on the heap, but because the underlying data structure is an object[], the data has to be boxed which means a pointer also has to be stored on the heap which requires more memory to be allocated.

The memory allocation for an ArrayList and a List<T> : class (a list of reference types) is exactly the same.

Charlie
@Charlie: Adding an integer to a `List<int>` puts the data *on the heap*, as an element of the list's internal array. The difference between `List<int>` and an `ArrayList` of `int` is, as you say, that the elements will not be boxed in the generic list.
LukeH
@Luke, thanks have updated.
Charlie
+5  A: 

List<T> is better than ArrayList:

An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur when storing or retrieving a value type. However, a List can have similar performance to an array of the same type if no reallocations are required; that is, if the initial capacity is a good approximation of the maximum size of the list.

From ArrayList and List Collection Types

Rubens Farias