Stack And Heap
PART 1
The Stack is care aboutwhat's executing in our code (beingcalled). The Heap is Care Aboutobjects created.
Think of the Stack as a series of boxes stacked one on top of the next. Wekeep track of what's going on in ourapplication by stacking another box on top every time we call a method (calleda Frame). We can only use what's in the top box on the stack. Whenwe're done with the top box (the method is done executing) we throw it away andproceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that itspurpose is to holdinformation (not keep track of execution most of the time) so anything inour Heap can be accessed atany time. With the Heap, there are no constraints as to what canbe accessed like in the stack.
The Stack is maintained by system thread . Whenthe top box is no longer used, it's thrown out. The Heap, is maintained by GC - which deals with how to keepthe Heap clean .
What goes on the Stack and Heap?
We have four main types of things we'll be putting inthe Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.
Value Types:
In C#, all the "things" declared with thefollowing list of type declarations are Value types (because they are fromSystem.ValueType):
Reference Types:
All the "things" declared with the types inthis list are Reference types (and inherit from System.Object... except, ofcourse, for object which is the System.Object object):
Pointers:
The third type of "thing" to be put in ourmemory management scheme is a Reference to a Type. A Reference is referred to as a Pointer. The pointers are managedby the CommonLanguage Runtime (CLR). A Pointer(or Reference) is different than a Reference Type in that when we say somethingis a Reference Type is means we access it through a Pointer. A Pointer isa space in memory that points to another space in memory. A Pointer can both put in Stack and Heap . its value is either a memory address or null.
Instructions:
You'll see how the "Instructions"work later in this article...
How is it decided what goeswhere?
Here are our two golden rules:
The Stack, as wementioned earlier, is responsible for the executionof our code (or what's been called). You can think of it asa thread"state" and each thread has its own stack. When call a method, thethread put instructions on the top of stack then executingand put the method's parameters on the thread stack. Then, as we go throughthe code and run into variables within the method they are placed on top of thestack.
Take the following method.
publicintAddFive(intpValue)
{
intresult;
result = pValue + 5;
returnresult;
}
Next, some thread is passed to the instructions to the AddFive()method which lives in our type's method table, a JIT compilation is performedif this is the first time we are hitting the method.
As the method executes, we need some memory forthe "result" variable and it is allocated on the stack.
The method finishes execution and our result isreturned.
step 1>Method instruction
step 2>Parameters
step 3>result
And all memory used bythe method is cleaned up by movinga pointer to the available memory address where AddFive() started and we godown to the previous method on the stack (not seen here).
In this example, our "result" variableis placed on the stack. As a matter of fact, every time a Value Type is declaredwithin the body of a method, it will be placed on the stack.
Now, Value Types are also sometimes placed on theHeap. Remember the rule, Value Typesalways go where they were declared. Well, if a Value Typeis declared outside of a method, but inside a Reference Type it will be placedwithin the Reference Type on the Heap.
Here's another example.
If we have the following MyInt class (which is aReference Type because it is a class):
publicclassMyInt
{
publicintMyValue;
}
and the following method is executing:
publicMyIntAddFive(intpValue)
{
MyInt result =newMyInt();
result.MyValue = pValue + 5;
returnresult;
}
Just as before, the thread starts executing themethod and its parameters are placed on the thread's stack.
Because Result Type--MyInt is a Reference Type , So it is placed on the Heap and referenced by a Pointer on theStack.
After AddFive() is finished executing (like in thefirst example), and we are cleaning up...
we're left withan orphaned MyInt in the heap .(waiting GC executing )
This is where the Garbage Collection (GC) comesinto play. GC will find all objects in the Heap that are not beingaccessed by the main program and delete them. The GC will then reorganizeall the objects left in the Heap to make space and adjust all the Pointers tothese objects in both the Stack and the Heap. As you can imagine, thiscan be quite expensive in terms of performance, so now you can see why it canbe important to pay attention to what's in the Stack and Heap when trying towrite high-performance code.
When we areusing Reference Types, we're dealing with Pointers to the type, not the thing itself. When we're using Value Types, we're using the thingitself.
If we execute the following method:
publicintReturnValue()
{
intx =newint();
x = 3;
inty =newint();
y = x;
y = 4;
returnx;
}
The Memory is allocated :
so We Got x= 3
However, if we are using the MyInt class frombefore
publicclassMyInt
{
publicintMyValue;
}
and we are executing the following method:
publicintReturnValue2()
{
MyInt x =newMyInt();
x.MyValue = 3;
MyInt y =newMyInt();
y = x;
y.MyValue =4;
returnx.MyValue;
}
The Memory allocated :
So We Got x=4
reference :http://www.c-sharpcorner.com/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx