Reputation: 481
I want to clear concepts regarding Memory allocation of ArrayList vs Generic List, if both are value type and if both are reference type. Could any one hhelp to clear out?
Upvotes: 1
Views: 2491
Reputation: 31077
They are both reference types. The only difference is that ArrayList
is weakly typed. Value types such as int, bool etc that are stored in it are boxed into the object
type. Then, you unbox them when you cast each item in the ArrayList
.
Because everything is boxed into an object, you can store objects of different types in an ArrayList
.
Generic List is strongly typed, that is, it can store objects of the same type. There's no boxing, so it's more efficient.
The boxing process allocates more memory to encapsulate the object into the weak type object
.
If you stored only objects of reference types in the ArrayList, then boxing is not used, rather another mechanism is used called reference conversion.
Upvotes: 1
Reputation: 273244
The only difference in memory use is when you store a Value type. The ArrayList will have to Box (copy) the value. A boxed value will be placed on the Heap, consuming at least an extra header block (ca 20 bytes).
But this will only be significant when you store many millions of items, not something you do all the time.
Upvotes: 2
Reputation: 9261
ArrayList
is a Reference Type,but not Typesafe and less efficientList<T>
or Generic list is a Reference Type,but is Type Safe and efficientHere is the SO post on Memory Allocation of Reference Types How memory is allocated to reference types in C#?
Upvotes: 0