Stack in. Net

Source: Internet
Author: User
Source:
Http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx

Although we do not need to worry about memory management and Garbage Collection in. NET framework, we should still understand them to optimize our applications. At the same time, we also need to have some basic knowledge of memory management mechanisms, which can help to explain the behavior of variables in our daily program writing. In this article, I will explain the basic knowledge of stacks and stacks, the types of variables, and why some variables can work in their own way.

In the. NET framework environment, when code is executed, there are two places in the memory to store the code. If you do not know, let me introduce Stack and Heap to you ). Stack and heap are used to help us run code. They reside in the machine memory and contain the information required for all code execution.

* Stack vs Stack: What is the difference?

Stack is responsible for saving our code execution (or call) path, while stack is responsible for saving the object (or data, next we will talk about a lot of heap problems) path.

Think of stacks as a pile of boxes stacked from top to bottom. Every time we call a method, we record what happens in the application in a box at the top of the stack, and each time we can only use the box at the top of the stack. When the box at the top of the stack is used up or the method is executed, we will leave the box and continue to use the new box at the top of the stack. The working principle of the heap is similar, but most of the time the heap is used to save information rather than save the execution path. Therefore, the heap can be accessed at any time. Compared with the stack, there is no access restriction on the stack. the stack is like the old clothes on the bed. We didn't take the time to sort it out, because we can find the clothes we need at any time, stack is like a shoe box stacked in a locker. We can only take it from the top-level box until we find that it is suitable.

 

It is not a real representation in the memory, but it can help us distinguish stack and heap.

Stack is self-maintained, that is, the memory automatically maintains the stack. When the box at the top of the stack is no longer used, it will be thrown out. On the contrary, garbage collection needs to be considered for the heap. Garbage collection is used to keep the heap clean. No one wants to see the clothes around it. It's so bad!

* What are the stacks and stacks?

During code execution, four types of data are stored in the stack and stack: Value Type, Reference Type, Pointer ), command (Instruction ).

1. Value Type:

In C #, all things declared as the following types are called value types:

Bool
Byte
Char
Decimal
Double
Enum
Float
Int
Long
Sbyte
Short
Struct
Uint
Ulong
Ushort

2. Reference Type:

All things declared as the following types are called reference types:

Class
Interface
Delegate
Object
String

3. pointer:

In the memory management solution, the third type is type reference, and the reference is usually a pointer. Pointers are not displayed. They are managed by the Common Language Runtime (CLR. A pointer (or reference) is different from a reference type because when we say that a thing is a reference type, it means that we access it through a pointer. A pointer is a piece of memory space, and it points to another memory space. Just like the stack and heap, the pointer also occupies the memory space, but its value is a memory address or is empty.

 

4. commands:

In the subsequent articles, you will see how commands work...

* How do I decide where to put it?

Here is a golden rule:

1. The reference type is always in the heap. (Simple enough ?)

2. value types and pointers are always placed in the places where they are declared. (This is a little complicated. You need to know how the stack works before you can determine where the stack is declared .)

As we mentioned earlier, stack is responsible for saving the path for code execution (or calling. When our code starts to call a method, it places an encoding instruction (in the method) on the stack, followed by the method parameters, then, the code is executed to the variable position from the method "Pressure stack" to the top of the stack. The following example makes it easy to understand...

The following is a Method ):
Copy C # code save code public int AddFive (int pValue)
{
Int result;
Result = pValue + 5;
Return result;
}

Now let's take a look at what happened at the top of the stack. Remember that the top of the stack we observe has been pushed into many other contents.

First, the method (only contains the logical bytes to be executed, that is, the command to execute this method, rather than the data in the method body) is imported into the stack, followed by the parameters of the method into the stack. (We will discuss more parameter transfer later)

 

Then, the control (that is, the thread of the execution method) is passed to the AddFive () Instruction in the stack,

 

When the method is executed, we need to allocate some memory for the "result" variable on the stack,

 

The method finishes execution and our result is returned.
Method execution is complete, and the result of the method is returned.

 

By pointing the stack pointer to the available memory address used by the AddFive () method, all the memory used by this method on the stack is cleared, and the program will automatically return to the position of the initial method call on the stack (not seen in this example ).

 

In this example, our "result" variable is placed on the stack. In fact, when the value type data is declared in the method body, they are all placed on the stack.

Value Type data is sometimes stored on the stack. Remember this rule-value types are always placed in the places where they are declared. Okay. If a value type data is declared in the method in vitro and exists in a reference type, it will be replaced by the reference type in the heap.

Let's look at another example:

Suppose we have such a MyInt class (it is a reference type because it is a class type ):
Copy C # code save code public class MyInt
{
Public int MyValue;
}
Then, execute the following method:
Copy C # code save code public MyInt AddFive (int pValue)
{
MyInt result = new MyInt ();
Result. MyValue = pValue + 5;
Return result;
}
As mentioned above, the parameters of methods and methods are placed on the stack. Next, the control is passed to the AddFive () Instruction in the stack.
 

Then there will be some interesting phenomena...

Because "MyInt" is a reference type, it will be placed on the stack, and a pointer reference pointing to the stack will be generated on the stack.
 

After the AddFive () method is executed, we will clear it...
 

We will keep the remaining lonely MyInt objects in the heap (no pointer pointing to the MyInt object will exist in the stack !)
 

This is where the Garbage Collector (GC) works. GC starts to work when our program reaches a specific memory threshold and we need more heap space. GC stops all running threads, finds all objects in the heap that are no longer accessed by the main program, and deletes them. GC then organizes all the remaining objects in the heap to save space, and adjusts all the pointers related to these objects in the stack and heap. You will surely think that this process is very performance-consuming, so you will know why we need to pay so much attention to the stack and stack, especially when writing high-performance code.

OK... This is great. How does it affect me?

Good question.

When we use a reference type, we are actually processing the type pointer, not the type itself. When we use the value type, we are using the value type itself. Sounds confused, right?

The example is the best description.

Assume that we execute the following methods:
Copy C # code save code public int ReturnValue ()
{
Int x = new int ();
X = 3;
Int y = new int ();
Y = x;
Y = 4;
Return x;
}
We will get the value 3, which is very simple, right?

Assume that we first use the MyInt class
Copy C # code save code public class MyInt
{
Public int MyValue;
}
Then, execute the following method:
Copy C # code save code public int ReturnValue2 ()
{
MyInt x = new MyInt ();
X. MyValue = 3;
MyInt y = new MyInt ();
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}
What will we get ?... 4!

Why ?... How does x. MyValue become 4 ?... Let's look at what we have done and then we know what is going on:

In the first example, everything is as planned:
Copy C # code save code public int ReturnValue ()
{
Int x = 3;
Int y = x;
Y = 4;
Return x;
}
 

In the second example, we do not get "3" because the variables "x" and "y" both point to the same object in the heap.
Copy C # code save code public int ReturnValue2 ()
{
MyInt x;
X. MyValue = 3;
MyInt y;
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}
 

We hope that the above content will give you a better understanding of the basic differences between the value type and the reference type in C #, and have a basic understanding of when pointers and pointers are used.

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: info-contact@alibabacloud.com 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.