Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contiguous memory storing misunderstanding in.net?

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


  1. 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)

  2. why Does List with structs is allocated in contiguous memory, unlike a List of classes ?

like image 770
Royi Namir Avatar asked Feb 07 '12 21:02

Royi Namir


1 Answers

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.

like image 185
Reed Copsey Avatar answered Nov 09 '22 10:11

Reed Copsey