Analysis of the difference between heap and Stack in C #

Source: Internet
Author: User

Thread stacks: Short Stack stack
Managed heap: Simply heap heap

Use. NET Framework Development program, we do not have to worry about memory allocation problems, because there is a GC this big butler gives us everything. If we write the following two pieces of code:

1 Code Snippet 1:2 3 public int addfive (int pValue) 4 {5 int result;6 result = PValue + 5;7 return result;8}
1 Code Snippet 2:2  3 public class MyInt 4 {5 public int myvalue, 6} 7  8 public MyInt addfive (int pValue) 9 {ten MyInt ResU lt = new MyInt (), one result. MyValue = PValue + 5;12 return result;13}

Question 1: Do you know how the pvalue and result in memory are stored in the code Snippet 1 at execution time, and what is the life cycle? What about Code Snippet 2?
If we want to make the above problem, we should be right. NET stack (stack) and the managed heap (heap) is a clear understanding of Benlee and Tao. If you want to improve program performance, understand stacks and heaps, you must!
This article starts with the stack and heap, type variable, and discovering the program we write.
When a C # program runs on the CLR, memory logically divides two chunks: stack, heap. These basic elements make up the operating environment of our C # program.

One, stack vs heap: The difference?

Stacks usually hold the steps that our code executes, such as the Addfive () method in code snippet 1, the int pvalue variable, the int result variable, and so on. And the heap is mostly objects, data and so on. (Translator Note: Ignore compiler Optimizations) we can think of stacks as a box that is stacked together. When we use it, each time we take a box from the top of the way. The same is true of stacks, when a method (or type) is called to complete, take away from the top of the stack (called a frame, call frame), and then next. Heap is not, like a warehouse, the storage of the various objects we use information, unlike the stack is that they are not immediately cleared out of the call

Stack memory does not need to be managed by us or by GC. When the top element of the stack is finished, it is released immediately. The heap requires a GC (garbage collection: garbage collector) cleanup.

Two, what elements are assigned to the stack? What is assigned to the heap?

When our program executes, there are four main types allocated in stacks and heaps: value types, reference types, pointers, directives.

Value type:
In C #, types that inherit from System.ValueType are referred to as value types, mainly in the following categories (the supported types in CLR2.0 are incremented):

* Byte
* Char
* Decimal
* Double
* enum
* Float
* Long
* SByte
* Short
* struct
* ushort

Reference type:
The following are reference types, inherited from System.Object:
* Class
* Interface
* Delegate
* Object
* String

In the memory area, a reference to a type, often referred to as a "pointer", is managed by the CLR (Common Language Runtime: Common language Runtime) and we cannot display it. It is important to note that a reference to a type is a pointer to a reference type that is two completely different concepts. The pointer occupies a chunk of memory in memory, which itself represents only one memory address (or null), and another chunk of memory that it points to is our real data or type.

Later, the instructions are introduced again.

Three, how to allocate?
Let's take a look at two ideas:
Point 1, the reference type is always allocated on the heap. Correct )
Point 2, value types and pointers are always assigned to the defined place, and they are not necessarily assigned to the stack. (This is a bit difficult to understand, need to take a slow look)

The stack, mentioned above, maintains a dedicated thread stack for each thread while the program is running.
When a method is called, the main thread starts in the metadata of the owning assembly, finds the called method, and then compiles the result (typically the local CPU instruction) on top of the stack by JIT-on-demand. The CPU takes instructions from the top of the stack via the bus, and the driver executes.

Let's go through the examples below.

Or are we beginning with the code Snippet 1:

1 public int addfive (int pValue) 2 {3 int result;4 result = PValue + 5;5 return result;6}

When the Addfive method starts executing, the method parameter (parameters) is allocated on the stack.

Next, the instruction points to the inside of the Addfive method, and if the method is executed for the first time, JIT-on-the-fly compilation begins.

When execution begins inside the method, the variable result is allocated on the stack, the method executes, and the area on the stack is cleaned up after the method returns.

As seen above, a value type variable is generally allocated on the stack. And what is the understanding of that point in 2? "Value types and pointers are always assigned where they are defined, and they are not necessarily assigned to the stack."
The reason is that if a value type is declared outside a method body and in a reference type, it is allocated on the heap.
or code Snippet 2:

1 public class MyInt 2 {3 publicly int myvalue; 4} 5  6 public MyInt addfive (int pValue) 7 {8 MyInt result = new MyInt (); 9 result. MyValue = PValue + 5;10 return result;11}

When the thread starts executing the Addfive method, the parameter is assigned to the stack, because Myint is a reference type, so it is assigned to the heap, and a pointer is generated on the stack (result), the memory on the stack is cleaned up when the Addfive method executes, and the heap is still present.

When the program requires more heap space, the GC needs to do garbage cleanup, pausing all threads, and finding all the unreachable objects, that is, no referenced objects, to clean up. and notifies the stack that the pointer is re-pointing to the object after the address is sorted. Now we should know that understanding stacks and heaps is important for us to develop high-performance programs. When we use reference types, it is generally the manipulation of pointers rather than the reference type object itself. The value type, however, operates on its own.
Next, let's illustrate this point with an example.

1 cases 1:2  3 public int returnvalue () 4 {5 int x = new int (); 6 x = 3; 7 int y = new int (); 8 y = x; 9 y = 4;10 return x ; 11}

The execution result is 3, slightly modified:

1 cases 2:2  3 public class MyInt 4 {5 public int myvalue, 6} 7  8 public int ReturnValue2 () 9 {MyInt x = new MyInt (); x.myvalue = 3;12 MyInt y = new MyInt (); y = x;14 Y.myvalue = 4;15 return x.myvalue;16}

The execution result is 4.

Let's analyze the reason, and its example 1 is the same as the following code:

1 public int returnvalue () 2 {3 int x = 3;4 int y = x;5 y = 4;6 return x;7}

X and y occupy a chunk of memory on the stack, each with no interference.

In Example 2, the following code is the same as the utility:

1 public int ReturnValue2 () 2 {3 MyInt x;4 x.myvalue = 3;5 MyInt y;6 y = x;7 y.myvalue = 4;8 return x.myvalue;9}


Summary: Value type variables are generally allocated on the stack, and if a value type is declared outside a method body and in a reference type, it is allocated on the heap.

Reference type variables are always allocated on the heap.

Stack does not need to recycle heap GC will be recycled

Analysis of the difference between heap and Stack in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.