Stack vs. Heap
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Contents |
The Stack
The stack is a data structure in memory used for storing items in a last-in, first-out manner (LIFO). The stack contains both local variables and the call stack. In C#, value types are stored on the stack.
Local variables
Local variables are variables that are declared inside a method. They can be of either value type or reference type. Value type variables are stored directly on the stack. A reference type variable is actually a numerical address pointing to a location on the heap where the object is stored.
Call stack
Every C# application begins with a Main method. In turn, it calls other methods which call still other methods. When a method is called, it is added to the top of the stack. And, when a method returns to its caller, it is removed from the stack. Execution continues with the calling method.
Scope
Scope defines the lifetime of a variable. The block of code in which a variable is declared is its scope. When the block in which a variable is declared begins execution, the variable's lifetime begins when it is pushed onto the stack as part of the call stack. When execution leaves the block in which the variable was declared, the call stack and variables are popped off the stack. The variable's lifetime has ended.
The Heap
The heap or managed heap is a data structure in memory where all objects—reference types—are stored. When an object is instantiated, the object is stored on the heap as a block of data containing its data members. Then, the memory address of the block is stored in a reference variable. Future references to the object are through the reference variable.
In C#, the new operator is used to instantiate a class and return the reference to the object on the heap.
MyClass myObject = new MyClass (); // declare and instantiate string bestSite = "C# Online.NET"; // declare and initialize
It is also possible for objects to contain references to other objects:
// Create an array on the heap string[] words = new string [10]; // words is a reference that exists on the stack as a 32 bit // pointer to a location on the heap // It refers to an object on the heap that contains 10 values // Since string is a reference type, each of the array items // is actually a reference to its own string object on the heap // Therefore, the words array object has 10 string reference // each of 4 bytes = 40 bytes Assert.IsTrue (sizeof (words) == 10 * 4); // Also, each string reference is initialized to null Assert.IsTrue (words[0] == null);
Summary
The following table summarizes the differences between the Heap and the Stack:
| Memory | Contents | Item Order | Item Lifetime | Item Removal | Timing |
| Stack | value types, stack frames | sequential (LIFO) | scope | pop | deterministic |
| Heap | objects | random | reference count | Garbage Collection | nondeterministic |