which one is more memory efficient?
which one works faster with 1000000 items?
is there anything better?
views:
103answers:
2A 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.
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.