[You must know. Net] (8) taste type-value type and reference type (on)-memory rational

Source: Internet
Author: User
[You must know. Net] (8) taste type --- value type and reference type (on)-memory rational

Author: anytao

 

 

This article introduces the following:

    • Basic concepts of Types
    • In-depth Value Type
    • In-depth reference type
    • Comparison and Application of Value Type and reference type

 

1. Introduction

I bought a new book and got busy with the system for several days. Finally, I started to give a comprehensive description of the value type and reference type. At the beginning of this series, I wanted to write this topic, to write a series. Therefore, the analysis of the value type and reference type is one of my most written articles. The reason is that in the past learning process, I started from this topic, I like to analyze and execute it in Il language, and I also like to learn more about the underlying process. For me, this seems to be a way to effectively improve, so the impulse to write is not stopped, and the purpose is to share the income in an effective way. At the same time, I also think that grasping the value type and reference type is a key topic in understanding the basic language, and it is necessary to make efforts to understand and deepen it.

2. Everything starts from memory

2.1 Basic Concepts

From the back to "7: taste type-starting from a general type system", we know that CLR supports two basic types: Value Type and reference type. Therefore, let's take the classic view of msdn as a foreshadowing.

 

Value Type instances are usually allocated to the stack of a thread and do not contain any pointer to instance data, because the variable itself contains its instance data. It is defined in msdn as a value type that directly contains their data. Value-type instances are either on the stack or Inline in the structure. We can see that the value types mainly include simple type, struct type, and enumeration type. Usually declared as the following types: int, Char, float, long, bool, double, struct, Enum, short, byte, decimal, sbyte, uint, ulong, ushort, etc, this variable is a value type.

The reference type instance is assigned to the managed heap instance. The variable stores the memory reference of the instance data. It is defined in msdn as a reference to the memory address of the reference type storage value, which is located on the heap. We can see that the reference type can be self-description type, pointer type, or interface type. The self-description type is further subdivided into arrays and class types. A class can be a user-defined class, a boxed value type, and a delegate. This variable is usually declared as a reference type when it is of the following types: Class, interface, Delegate, object, string, and other custom reference types.

Next we will briefly list the further subdivisions of our types. The data comes from msdn, so that we can have a clear type concept. This is the most basic and necessary content.

2.2 memory depth

2.2.1. Memory Mechanism

So what is the memory allocation mechanism of. Net?

The data allocation location in the memory depends on the Data Type of the variable. It can be seen from the above that the value type is usually allocated on the thread stack, and the reference type is usually allocated on the managed stack, which is controlled by GC. For example, mystruct and myclass represent a struct and a class respectively, as follows:

Using system;

Public class test
{
Static void main ()
{
// Define the value type and reference type, and complete Initialization
Mystruct = new mystruct ();
Myclass = new myclass ();

// Define another value type and reference type,
// To understand the memory difference
Mystruct mystruct2 = new mystruct ();
Mystruct2 = mystruct;

Myclass myclass2 = new myclass ();
Myclass2 = myclass;
}
}

In the above process, we define the value type variable mystruct and reference type variable myclass respectively, and use the new operator to complete memory allocation and initialization, for details about the differences between new and new, refer to the Fifth Review: A simple keyword-a new statement, which is not further described here. Here we emphasize the differences between mystruct and myclass variables in memory allocation. We will also look at a concise figure:

 

We know that every variable orProgramEach has its stack, and different variables cannot share the same stack address. Therefore, mystruct and mystruct2 must occupy different stack addresses in the stack, even though they are passed through variables, the actual memory is still allocated to different addresses. If we change the mystruct2 variable, the data of mystruct is obviously not affected. We can also clearly see that mystruct contains its instance data in the stack, while myclass only saves the reference address of its instance data in the stack, and the actual data is saved in the managed heap. Therefore, different variables may store data references of the same address. when data is transferred from one referenced type variable to another referenced type variable of the same type, it transmits the reference address rather than the actual data. Therefore, a change to a variable affects the value of another variable. From the above analysis, we can understand the simple principle: the difference between the value type and the allocation of the reference type in the memory determines the root cause of different applications, therefore, we can easily explain why the parameter value does not change the parameter value when it is passed, but the value of the row parameter is changed when it is passed by address. This is the reason.

For more detailed memory allocation locations, you can describe them as follows:

    • When the value type variable is a local variable, the instance will be created on the stack. If the value type variable is a member variable of the type, it will be part of the data of the type instance, other fields of the same type are stored on the managed stack. This will be detailed in the subsequent nested structure section.
    • The reference type variable data is stored on the managed stack, but varies according to the instance size as follows: if the instance size is smaller than 85000byte, the instance will be created on the GC stack; when the instance size is greater than or equal to 85000byte, the instance is created on the LOH (large object heap) stack.

For more detailed analysis, I recommend "create location of Type instances and structure of managed objects on managed stacks".

2.2.2. nested Structure

The nested structure refers to the nested definition of the reference type in the value type, or the nested definition of the value type in the reference type variable. I believe there are not many discussions and concerns about this topic in the garden. Therefore, it is necessary for us to give full play to it. Here, we can easily understand the. NET memory mechanism from the above. Net memory mechanism.

    • Reference Type nested Value Type

If the value type is nested in the reference type, that is, what is the memory allocation of the value type in the inline structure? In fact, it is very simple. For example, if a private field of a class is of the value type, it is also allocated as part of the reference type instance on the managed stack. For example:

Public class nestedvalueinref
{
// Aint will be allocated to the managed stack as part of the reference type
Private int aint;
Public nestedvalueinref
{
// Achar is allocated to this segment. Code On the thread Stack
Char Achar = 'a ';
}
}

Its memory distribution chart can be expressed:

    • Value Type nested reference type

When the reference type is nested in the value type, the memory allocation is as follows: This reference type will be used as a value type member variable, and the reference of this Member will be saved on the stack, the actual data of members is stored in the managed heap. For example:

Public struct nestedrefinvalue
{
Public myclass;
Public nestedrefinvalue
{
Myclass. x = 1;
Myclass. Y = 2;
}
}

Its memory distribution chart can be expressed:

 

2.2.3. A Simple Discussion

Through the above analysis, if we have the following execution:

AType [] mytype = new Atype [10];

Q: How much memory is allocated if Atype is a value type, and how much memory is allocated if Atype is a reference type?

Our analysis is as follows: According to the CRL memory mechanism, we know that if atpye is of the int32 type, its element is of the value type, and the array itself is of the reference type, mytype will save a memory address pointing to a 4 × 10 bytes in the managed heap, and assign all elements to 0. If Atype is a custom reference type, only one memory allocation is performed. A reference pointing to the managed heap is created in the thread stack, and all elements are set to null, which indicates null.

Not finished. The next release is coming soon...


 

References

(USA) Jeffrey Richter, applied Microsoft. NET Framework programming

(USA) David Chappell, understanding. net

All in one

This article is a little long, so it will be split into two parts. We have analyzed the type of memory mechanism. Next we should focus on the actual application fields of the type, therefore, in the next round, we will focus on [general rules and differences], [instance analysis], [application scenarios], and [type comparison, I hope to help you. I would be very grateful if I have any mistakes in expressing or understanding.

To be continue soon...

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.