There’s two type of memory that we should know. Stack and Heap, what’s the difference ?
Stack
- keeps track of the code execution contains
- it uses LIFO structure
- high performance memory, fixed limit
- local variables goes to stack
- points to an object in heap
Heap
- It’s a large pool of operating system memory
- used in dynamic memory allocation
- garbage collector remove any resources that no longer used
let’s take a look on how stack and heap works
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public void Go() { MyInt x = new MyInt(); x.MyValue = 2; DoSomething(x); Console.WriteLine(x.MyValue.ToString()); } public void DoSomething(MyInt pValue) { pValue.MyValue = 12345; } |
when that method is called, this what’s happening in the stack
- The Go() method is called
- the x local variable is defined and goes to the stack, x is a pointer that point to MyInt instance in the heap
- MyValue property is set, the value is stored in heap because MyValue is declared on the heap
- DoSomething() method is called
- the MyValue value in the heap is changed to 12345
references:
https://www.youtube.com/watch?v=clOUdVDDzIM
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx