Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for collections in .NET

This might be a dupe. I did not find enough information on this.

I was discussing memory allocation for collections in .Net. Where is the memory for elements allocated in a collection?

List<int> myList = new List<int>();

The variable myList is allocated on stack and it references the List object created on heap.

The question is when int elements are added to the myList, where would they be created ?

Can anyone point the right direction?

like image 945
AlwaysAProgrammer Avatar asked Dec 23 '22 02:12

AlwaysAProgrammer


2 Answers

The elements will be created on the heap. The only thing that lives on the stack is the pointer (reference) to the list (List<> is a reference type)

like image 91
Philippe Leybaert Avatar answered Dec 28 '22 06:12

Philippe Leybaert


The elements will also reside in the heap (in an array, that's how List works internally).

In principle, only local variables and arguments are be allocated on the stack and everything else goes on the heap (unless you use rare things such as stackalloc, but you don't need to worry about that)

like image 20
Matti Virkkunen Avatar answered Dec 28 '22 06:12

Matti Virkkunen