[CLR via C #] 5.3 value-type packing and unpacking

Source: Internet
Author: User
Tags unpack

In CLR, to convert a value type into a reference type, you must usePacking.

The following summarizes what happens inside an instance of the value type when it is packed: 1) allocate memory in the managed heap. The amount of memory allocated is the amount of memory required for each field of the Value Type plus two additional members for all objects on the managed stack ( Type object pointerAnd Synchronize block Indexes) The amount of memory required. 2) Copy fields of the value type to the allocated heap memory. 3) return the object address. Now, this address is a reference to an object, and the value type is now a reference type. UnpackInstead of directly dumping the packing process. The cost of unpacking is much lower than that of packing. Unpacking is actually a process of getting a pointer that points to the original value type (data field) contained in an object ). In fact, the Pointer Points to the unpacked part of the boxed instance. Therefore, unlike packing, unpacking does not require copying bytes in the memory. Another key point is, After unpacking, a copy operation is usually performed immediately after the field is split.When unpacking an object, you can only convert it to The value type when the original is not packed, as shown below:
  = = x= (Int16) o;}

  = = x;                 Int16 y = (Int16) (Int32) o; }

After unpacking, fields are often copied immediately. The following demonstrates the unpacking and copying operations:

      p.x = p.y =  o = p;              p = (Point) o;         }

In the last line, the C # compiler will generate an IL command to unpack o and generate another IL command to copy these fields from the heap to the stack-based Variable p.

Let's take a look at the example of packing and unpacking:

   Main(= ;                 Object o = v;                v = ;                     Console.WriteLine(v +  + (Int32)o);  }

How many times have the above Code been packed? If it was three times, would you mean it? Let's take a look at the generated IL code.

.method  hidebysig   Main(    .maxstack ]     L_0001: ldc.i4.         L_0003: ldloc.         L_000a: ldc.i4.s          L_000d: ldloc.    L_0013: ldstr         L_0018: ldloc.    L_0023: call  [mscorlib]System.String::Concat(, ,     L_0028: call 

Tip: The main cause is the Console. WriteLine method.

The Console. WriteLine method requires obtaining a String object. To create a String object, C # compiler generates code to call the static Concate method of the String object. This method has several overloaded versions. The only difference is the number of parameters. In this example, three data items need to be connected to create a string. Therefore, the compiler will choose the following Concat method to call it:

  String Concat(Objetc arg0, Object arg1, Onject arg2);

Therefore, if you write a call to WriteLine as follows, the generated IL code will have a higher execution efficiency:

Console.WriteLine(v +  + o);  

This only removes the (Int32) forced conversion before the variable o. This avoids unpacking and packing.

We can also call WriteLine to further improve the performance of the above Code:

Console.WriteLine(v.ToString() +  + o);  

Now, the ToString method is called for the value type instance v, which returns a String. The String type is already a reference type, so it can be directly passed to the Concat method without any packing operation.

The following shows how to pack and unpack a box:

   Main(= ;                       Object o = v;                     v = ;                            Console.WriteLine(v)        v = (Int32) o;                    Console.WriteLine(v);  }

How many times have the above Code been packed? The answer is once. Because the System. Console class defines an overloaded version of The WriteLine method that gets an Int32 as the parameter:

  String Concat(Int32 value);

The packing operation may occur inside the WriteLine method, but this is beyond our control. We have removed the packing operation from our code as much as possible.

Finally, if you know that the code you write will cause the compiler to repeatedly bind a value type, use the manual method to pack the value type.

  

          (  == obj )           

The following shows how to correctly implement an Equals method internally. 1) if the obj real parameter is null, false is returned, because when the non-static Equals method is called, the current object identified by this is obviously not null. 2) If this and obj parameters reference the same object, true is returned. This step helps improve performance when comparing objects with a large number of fields. 3) If this and obj parameters reference different types of objects, false is returned. A String object is obviously not equal to a FileStream object. 4) Compare the value in this object with the value in obj object for each instance field defined by the type. If any field is not equal, false is returned. 5) Call The Equals method of the base class to compare any fields it defines. If the base class Equals method returns false, false is returned; otherwise, true is returned. For example:
           (obj ==  )           (.GetType() != obj.GetType())           

  ==

System. ValueType (base classes of all value types) overrides the Equals method of the Object and implements the equality check correctly.

Related Article

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.