NET types and boxing/unboxing principles

Source: Internet
Author: User

When it comes to packing and unpacking, Debuglzq believes that the Bo friends in the garden must be able to tell the way, presumably meaning that the value type and the reference type of the mutual conversion of the---value type to the reference type is called boxing, the other is called unboxing. This certainly no problem, but you only know so much, then debuglzq suggest you take some time to see the landlord this article, continue the previous several blog style--talk about miscellaneous Kan.

1.. The types in net

To illustrate boxing and unpacking, you first have to say the type. In. NET, we know that the System.Object type is the base class for all built-in types. Note that this is said to be built-in type, programmers can write non-inherited sub-System.Object type, here do not do too much introduction (interested Bo friends can study).

All. NET types can be divided into two categories (a bit less rigorous, but everyone says): value types and reference types. So how do value types and reference types differentiate, and what is the standard? The simplest and most unambiguous criterion is that all value types inherit from System.ValueType (System.ValueType inherits from System.Object), which means that All types that inherit from System.ValueType are value types, and other types are reference types. (digression: In a previous reading, "You must know. NET", he says, the most essential difference between a value type and a reference type is that the value type and the reference type are allocated in memory, the former is allocated on the stack, and the latter is allocated on the heap. Personally, this is not a simple and definite way to differentiate. Far from the DEBUGLZQ said so explicit! )

Speaking of which, you should have this idea: strictly speaking, System.Object as the base class for all built-in types, there is no value type and no reference type in itself. However, System.Object objects have the characteristics of reference types. This is why value types need to be boxed in some cases.

The following is still a simple value type and reference type of the different places, divided into 3 pieces, personally feel that the understanding of the 3 pieces can be:

    1. Variable assignment value type of variable will directly get a real copy of the data, and the assignment of reference type only is the object reference to the variable, which may result in a number of variables referenced to a Real object instance (here you need to understand the Bo friends. NET to some of the optimization mechanisms of string, nature and this does not contradict).
    2. Objects of the memory allocation reference type will allocate memory on the heap, whereas objects of value types will allocate memory on the stack. (How memory is allocated: What is stored on the stack? A reference to a value-type variable and a reference-type variable.) What's on the heap? Objects of the reference type (including the type object pointer and the synchronization block index, note that it is just an index, which is. NET is a compromise approach proposed for thread synchronization. ))。 A large object heap (also a heap, a special heap) or something is not introduced here. But it must be said that the space of the stack is limited, but the efficiency is much higher than the heap!!!
    3. Since all value types inherit from System.ValueType, and System.ValueType inherits from System.Object, and a virtual method of the base class System.Object is re-implemented by equals, the reference type is not overridden.
2. Packing and unpacking principle

A brief introduction to the previous. NET, the following is the introduction of boxing and unpacking. By 1 We know that objects of value types are allocated memory on the stack, whereas reference types (including System.Object) objects are allocated memory on the heap, then when the type of the values is cast, a series of operations are performed on the stack and heap, which is the source of the boxing unboxing.

A good understanding of the principle of packing and unpacking helps us programmers write efficient code.

Comb under: Before Debuglzq said, all value types inherit from System.ValueType, and Sytem.valuetype inherit from System.Object; All value type objects are allocated on the stack, and all reference types, Of course including System.Object, objects are allocated on the heap. So, the question is: Since System.Object is the base class for all value types, then all value types must implicitly be converted to System.Object (the type substitution principle in object-oriented, the base class can replace subclasses), so where will this object be allocated, on the heap or on the stack? In fact, when this transition occurs, the CLR needs to do extra work to move the value types on the stack to the heap, which is what we call "boxing."

Detailed steps for packing (box):
    1. Allocates a memory space on the heap that is equal to the size of the value type object that needs to be boxed plus the members that are owned by two reference type objects: type Object pointer and synchronous block reference.
    2. Copies the value type object on the stack to the newly allocated object on the heap.
    3. Returns a reference to a new object on the heap and stores it in an object of that value type that is boxed on the stack.

This step does not need to be written by the programmer, and the compiler automatically adds the IL code that performs the above functions in any place where the boxing occurs.

The so-called unboxing is the concept of boxing, but the unpacking process and boxing is not the reverse is:

Detailed steps for unpacking (Unbox.any)

Throws a NullReferenceException exception if the object to be unboxing is null.

Throws a InvalidCastException exception if the reference points to a boxed object that is not a desired object.

    1. Gets the address of each field in the boxed object, the process is "unpacking"

It is necessary to note that the general unpacking will be accompanied by the object copy, but the copy operation is not the scope of unpacking.

New performance comparison of packing and unpacking

Knowing the boxing and unpacking operations, we can clearly understand that the boxing operation will cause the data to be copied on the heap and stack, and the frequent boxing operation will lose the performance. In contrast, the unboxing process is relatively small in terms of performance loss.

3 Summary

Boxing and unpacking means a series of operations on heap and stack space, and there is no doubt that the performance cost of these operations is significant, especially with respect to the space on the heap, which is much slower than the stack and can cause garbage collection, all of which will affect the system on a large scale.

Packing and unpacking operations often occur in the following cases:

    • Formatted output of value type
    • System.Object Types of containers

In the first case, the formatted output of the type is often accompanied by a boxing operation, such as:

Using System;namespace maxvaluetest{//<summary>//DEBUGLZQ//    http://www.cnblogs.com/ DEBUGLZQ    //</summary> class program    {        static void Main (string[] args)        {            int i = Int32.MaxValue;            Console.WriteLine (The maximum value of "Int32" is "+i");//raises an unnecessary boxing operation            Console.WriteLine ("The maximum value of Int32 is" + i.tostring ());//ok                        Console.readkey ();}}}    

The second case is more common, such as a commonly used container ArrayList, which is a typical System.Object container, where any value type is placed into the ArrayList object, a boxing operation occurs, and the corresponding fetch value type Object raises a unboxing operation.

After the introduction of the concept of "generics" in. NET 2.0, these problems have been effectively addressed. Generics allow you to define containers for a particular type, including value types, and avoid boxing and unpacking.

For the mechanism and principle of generics, please follow the post of Debuglzq: "Talking about." NET in the mechanism and principle of generics, please look forward to ~

NET types and boxing/unboxing principles

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.