Reputation: 148534
http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx
I know that Arrays
in .net
is stored in a contiguous fashion. ( in mem)
I also know that List<..>
is not. ( well...not all list types... see at my 2'nd question)
From here I have 2 qustions
I know that after 4,8,16... inserted items to a list - the list reallocate
itself in memory.
I also know I can send him the Capacity
in ctor in order to let him know in what size im gonna create him ( to reduce re-allocation).
The question is why ? he Doesn NOT store itself contiguously , so why does he care about re- allocating himself ? ( he doesnt have to find free & contiguous memory cells)
why Does List with structs is allocated in contiguous memory, unlike a List of classes ?
Upvotes: 10
Views: 11322
Reputation: 9244
1) all the object references are still stored contigously
2) a list och classes still must let the objects be stored like ordinary objects. thay cannot be forced into a contigious array - but the references to them can
Upvotes: 0
Reputation: 564433
List<T>
does store memory contiguously. Internally, it uses an array for its storage. When you reach the capacity, a new array is allocated and the memory is copied.
This is true for List<T>
instances of classes or structs. However, when T
is a reference type (class), you're storing a contiguous list of references. The class instances cannot be contiguous as you can include a list which contains 100 references to the same instance of a class.
As such, to address your specific questions:
The question is why ? he Doesn NOT store itself contiguously , so why does he care about re- allocating himself ?
It does store the items contiguously, which is why the reallocation is required.
why Does List with structs is allocated in contiguous memory, unlike a List of classes?
Both are stored contiguously, but in the second case (classes) you're storing a list of references to a class instance.
Upvotes: 26