Stack and stack

Source: Internet
Author: User

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

Although in. NET
Framework, we do not need to worry about memory management and garbage collection, but we should still understand them to optimize our applications. Same
You also need to have some basic knowledge of memory management mechanisms, which can help explain the behavior of variables in our daily program writing. In this article, I will explain the basic knowledge of stacks and stacks, variable types, and
Why do some variables 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.

*StackVsHeap: 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 is going to happen in the application in a box at the top of the stack, and each time we can only use
The box. 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 heap works in a similar way, but most of the time
The heap is used to save information rather than to save the execution path. Therefore, the heap can be accessed at any time. Compared with the stack, the stack has no access restrictions. The stack is like the old clothes on the bed. We didn't take the time to sort it out. That's because we can
Find the clothes we need at any time, and stack is like a shoe box stacked in the locker. We can only start from the top box until we find that it is the right one.

[Heapvsstack1.gif]

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 does stack and stack have?

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. Pointer (or reference
Is different from the reference type, because when we say that a thing is a reference type, it means that we access it through pointers. A pointer is a piece of memory space, and it points to another memory space. Just like
Like a stack and a heap, a pointer also occupies memory space, but its value is a memory address or is empty.

[Heapvsstack2.gif]

4.Command:

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

*How to decide where to put?

Here is a golden rule:

1.The reference type is always in the heap.(Is it simple enough ?)

2.Value types and pointers are always placed in the declared places.(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 ):

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)

[Heapvsstack3.gif]

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

[Heapvsstack4.gif]

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

[Heapvsstack5.gif]

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

[Heapvsstack6.gif]

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 ).

[Heapvsstack7.gif]

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 ):

Public class MyInt
{
Publicint MyValue;
}

Then, execute the following method:

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.

[Heapvsstack8.gif]

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.

[Heapvsstack9.gif]

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

[Heapvsstack10.gif]

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

[Heapvsstack11.gif]

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
There are running threads. Find all objects in the heap that are no longer accessed by the main program and delete them. Then GC re-organizes all the remaining objects in the heap to save space, and adjusts all the objects in the stack and
Some object-related pointers. 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?

Goodquestion.

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:

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

Public class MyInt
{
Public int MyValue;
}

Then, execute the following method:

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:

Public int ReturnValue ()
{
Int x = 3;
Int y = x;
Y = 4;
Return x;
}

[Heapvsstack12.gif]

In the second example, we do not get "3" because the variables "x" and "y" both point to the same object in the heap.
Public intReturnValue2 ()
{
MyInt x;
X. MyValue = 3;
MyInt y;
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}

[Heapvsstack13.gif]

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. In the next part of the series, we will go deep into memory management and discuss the method parameters.

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

Although in. NET
Framework, we do not need to worry about memory management and garbage collection, but we should still understand them to optimize our applications. Same
You also need to have some basic knowledge of memory management mechanisms, which can help explain the behavior of variables in our daily program writing. In this article, I will explain the basic knowledge of stacks and stacks, variable types, and
Why do some variables 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.

*StackVsHeap: 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 is going to happen in the application in a box at the top of the stack, and each time we can only use
The box. 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 heap works in a similar way, but most of the time
The heap is used to save information rather than to save the execution path. Therefore, the heap can be accessed at any time. Compared with the stack, the stack has no access restrictions. The stack is like the old clothes on the bed. We didn't take the time to sort it out. That's because we can
Find the clothes we need at any time, and stack is like a shoe box stacked in the locker. We can only start from the top box until we find that it is the right one.

[Heapvsstack1.gif]

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 does stack and stack have?

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. Pointer (or reference
Is different from the reference type, because when we say that a thing is a reference type, it means that we access it through pointers. A pointer is a piece of memory space, and it points to another memory space. Just like
Like a stack and a heap, a pointer also occupies memory space, but its value is a memory address or is empty.

[Heapvsstack2.gif]

4.Command:

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

*How to decide where to put?

Here is a golden rule:

1.The reference type is always in the heap.(Is it simple enough ?)

2.Value types and pointers are always placed in the declared places.(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 ):

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)

[Heapvsstack3.gif]

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

[Heapvsstack4.gif]

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

[Heapvsstack5.gif]

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

[Heapvsstack6.gif]

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 ).

[Heapvsstack7.gif]

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 ):

Public class MyInt
{
Publicint MyValue;
}

Then, execute the following method:

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.

[Heapvsstack8.gif]

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.

[Heapvsstack9.gif]

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

[Heapvsstack10.gif]

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

[Heapvsstack11.gif]

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
There are running threads. Find all objects in the heap that are no longer accessed by the main program and delete them. Then GC re-organizes all the remaining objects in the heap to save space, and adjusts all the objects in the stack and
Some object-related pointers. 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?

Goodquestion.

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:

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

Public class MyInt
{
Public int MyValue;
}

Then, execute the following method:

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:

Public int ReturnValue ()
{
Int x = 3;
Int y = x;
Y = 4;
Return x;
}

[Heapvsstack12.gif]

In the second example, we do not get "3" because the variables "x" and "y" both point to the same object in the heap.
Public intReturnValue2 ()
{
MyInt x;
X. MyValue = 3;
MyInt y;
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}

[Heapvsstack13.gif]

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. In the next part of the series, we will go deep into memory management and discuss the method parameters.

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.