Understanding of stack and hosting heap as well as packing and unpacking

Source: Internet
Author: User
Tags float double unpack

The types in C # all come from the system. Object type, which can be the value type and reference type, which exist in the memory stack and the managed heap respectively,

Value types are generally simple types, such as int float double. They are stored in the stack and are a data structure that stores data items according to the following LIFO principles.

In computer systems, the stack refers to a memory area supported by the processor, where local variables are stored. The working method is to allocate the memory variable first and then release it (first, then, out ),

So once the scope is out, it will be released, so it cannot be used in the entire project. At this time, we thought of hosting the heap.

Stack (managed stack) Storage reference type. This heap is not another heap, And the heap in. NET is automatically managed by the garbage collector. Unlike the stack, the stack is allocated from the bottom up, so free space is on the top of the used space.

Let's take an example to see how data is stored in the memory through stacks and managed stacks.

Int A = 100;

In the heap stack, a space is allocated to save a, and the value is 100. Now there is a method.

Int getnum (int B)

{

  B = 500;

  Return B;

}

At this time, the value of a is passed as a parameter to this method. Will the value of a change be 500 at this time? This is the problem we will focus on. The method is temporary,

Once used up, it will be released. In fact, we just copied a A to the method, and the value of all a will not change.

Student Stu = new student ();

We know that the above is a variable of the reference type, and its internal process is

First, separate a space in the stack to put the reference of student Stu, and then place the new student (), that is, the object Stu, In the heap, her address is saved to the reference of student Stu, as shown in figure

Therefore, if a method uses a variable of the reference type as a parameter, as shown above, her value will change because its parameter is just a reference, for example, a person is a reference,

General familiarity is included in people. If people are familiar with changes, their specific objects will also change. Next let's take a look at their understanding of packing and unpacking:

1. packing and unpacking are an abstract concept.
2. binning converts the value type to the reference type, and unboxing converts the reference type to the value type.

3. Why packing? (Why convert the value type to the reference type ?)
One of the most common scenarios is to call a method containing parameters of the object type. This object can support any type for general purpose. You need to pack a value type (such as int32.
Another method is to define an element type as an object to ensure the universality of a non-generic container. Therefore, to add the value type data to the container, You need to pack

4. What is packing/unpacking?
Packing: used to store value types in the garbage collection heap. Packing is an implicit conversion between the value type and the object type or any interface type implemented by this value type.
Unpacking: the explicit conversion from the object type to the value type or from the interface type to the value type of the interface.

Packing:

  Step 1: allocate new managed heap memory (size: Value Type instance size plus a method table pointer and a syncblockindex ).
Step 2: copy the instance field of the value type to the newly allocated memory.
Step 3: return the address of the newly allocated object in the managed heap. This address is a reference to the object.

 For example:

   Int A = 100;

   Object o = A; (boxed)

   A = 200;

   This process is to allocate a memory in the managed heap, copy an instance of a from the stack to the memory just allocated in the managed heap, and finally return the address to the stack for storage.

In the memory, the address points to the object reference, so no matter how you change the O value of A, the O value will not change. On the contrary, the value of O value a will not change because they store different addresses.

Unpack:

Check the object instance to make sure it is a boxed value of the given value type. Copy the value from the instance to the value type variable. Note that only objects that have been packed can be split. Otherwise, an exception may occur.

For example, you can unpack the above object:

A = (INT) O;

In this way, the o Instance value is assigned to a, the lake, or a new memory space is allocated to store J

Int J = (INT) O;

6 effect of packing/unpacking on execution efficiency
Obviously, from the principle, we can see that during packing, a brand new reference object is generated, which may result in time loss, that is, reduced efficiency.
What should we do?
First, try to avoid packing.
For example, you can avoid both of the above two cases. In the first case, you can avoid this by using the overload function. In the second case, you can avoid using generics.
Of course, everything cannot be absolute. If the code you want to transform is a third-party assembly and you cannot change it, you can only pack it.
For the optimization of packing/unpacking code, since C # is implicit in both packing and unpacking, the fundamental method is to analyze the code, the most direct method of analysis is to understand the principle.

View the decompiled il code. For example, there may be extra packing in the loop body. You can simply use the advance packing method for optimization.

7. The general type System (CTS) has two basic types: Value Type and reference type. The fundamental difference between them lies in the way they are stored in memory .. Net uses two different physical memory blocks for storage

Data-stack and managed Stack

The 8-Value Type always occupies a predefined number of bytes in the memory (for example, the int type occupies 4 bytes, the number of bytes occupied by the string type varies according to the length of the string.) When a value type is declared

When a variable is used, the appropriate memory size will be allocated to the stack (except for reference type value type members, such as the int field of the class ), this space in the memory is used to store the values contained in the variable .. Net maintains a stack pointer, which

Contains the address of the next available memory space in the stack. When a variable leaves the scope, the stack pointer moves down the number of bytes occupied by the released variable, so it still points to the next available address

9 The reference variable also uses the stack, but the stack only contains the reference to another memory location, rather than the actual value. This location is an address in the managed heap. Like the stack, it also maintains a pointer, including

The address of an available memory space. However, the heap does not come in and out first, because the reference to the object can be passed in our program (for example, passed as a parameter to the method call ), objects in the heap will not be previewed in a program.

Click to exit the scope. To release the heap-allocated memory,. Net periodically collects garbage. The garbage collector recursively checks all object references in the application. Reference the inner of an object that is no longer valid

Memory cannot be accessed from the program, and the memory can be recycled.

10 The reference type contains a pointer pointing to the location of the storage object in the heap. Because the reference type only contains references and does not contain actual values, any modifications made to the parameters in the method body will affect the variables of the reference type passed to the method call.

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.