Stack VS Heap

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

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

  1. The Go() method is called
  2. the x local variable is defined and goes to the stack, x is a pointer that point to MyInt instance in the heap
  3. MyValue property is set, the value is stored in heap because MyValue is declared on the heap
  4. DoSomething() method is called
  5. 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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s