Easily learn the packing and unpacking of C

  • 2021-08-21 21:15:37
  • OfStack

First, look at 1. What are packing and unpacking?
Simply put:
Boxing is the conversion of a value type to a reference type;
Unpacking is the conversion of a reference type to a value type.
Value types, including original types (Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Char, Float, Double, Bool, Decimal), enumeration (enum), structure (struct).
Reference types include classes, arrays, interfaces, delegates, strings, and so on.

Boxing: Implicit conversion of a value type to a reference type or to any interface type implemented by this value type
For example: int temp = 3;
System. Object obj = temp;
Among them, temp is a value type and is allocated in the stack; When assigning the reference type obj, we need to assign an obj object in the heap, and then assign the temp value to it. This series of procedures is the boxing process.

Unpacking: An explicit conversion from a reference type to an arbitrary value type. Unlike packing, unpacking display conversion.
For example: int temp = 3;
System. Object obj = temp;
int i = (int) obj;
In the unpacking process, first determine that the object obj is a boxed value of 1 value type, and then assign the value to the value type.
Implicit conversion always succeeds and no exception is thrown:
(1) From a derived class to a base class;
(2) From the derived interface to the base interface;
(3) From class to interface (this class implements the interface);
(4), from Null to any class;
Explicitly refer to the conversion, and the following may throw an exception, and the conversion will not succeed:
(1) From base class to derived class;
(2) From interface to interface (base interface to derived interface or no relationship between two interfaces);
(3) From interface to class (the class implements the interface or the class is not closed);
(4) From class to interface (this class does not implement this interface and this class is not closed);

The definition of unpacking and packing is briefly introduced above, and how to use packing and unpacking with heap and stack is discussed below
Among them, the value type allocates memory in the stack, and its declaration is an initialization process, which does not need garbage collection. As long as it exceeds the defined scope, it will automatically release memory, while the reference type is allocated in the heap. Like java1, it allocates memory in the heap, while its managed heap carries out garbage collection. When the two data types are converted, packing/unpacking is introduced.
Compare the advantages and disadvantages of packing and unpacking
Boxing and unpacking satisfy the conversion between the two types. However, it is not difficult to see from the packing process that there are new1 new objects in the heap every time you pack, and the extremely large equivalent will definitely greatly affect the efficiency of the program. Things always have two sides, every sword has two sides, things are simple and performance is down. Therefore, in application, we should try to avoid packing operation.
Knowing the packing and unpacking operations, we can clearly understand that packing operations will cause data to be copied on the heap and stack, and frequent packing operations will lose performance. In comparison, the performance loss of unpacking process is relatively small.
Detailed steps for packing and unpacking

1. Detailed steps of packing (box):

(1) Allocate 1 memory space on the heap equal to the size of the value type object to be boxed plus the members owned by both reference type objects: type object pointer and synchronous block reference.
(2) Copy the value type object on the stack to the newly allocated object on the heap.
(3) Returns 1 reference to the new object on the heap and stores it in the object of the value type that is boxed on the stack.
This step does not need to be written by the programmer himself, and the compiler will automatically add IL code to perform the above functions wherever boxing occurs.
The so-called unpacking is the concept corresponding to packing, but the process of unpacking and packing is not reversed:
2. Detailed steps of unpacking (unbox.any)
If the object to be unpacked is null, an NullReferenceException exception is thrown.
Throws an InvalidCastException exception if the reference points to a boxed object that is not one of the expected objects.
(1) Get the address of each field in the boxed object. This process is "unpacking"
It should be noted that after 1 unpacking, it will be accompanied by the copy of objects, but the copy operation is no longer the category of unpacking.

Here are two small examples to realize what packing and unpacking are and how to avoid consuming memory due to frequent packing
(1) Packing:


 using System;
    public class Test
    {
          public static void Main(String[] args)
         {
             int i = 10;
             // Object of the value type i Packing 
             // It should be noted that : The packing here uses a copy of the value 
             object obj = i;
             // Check whether the packing is successful 
             if(obj is int)
             {
                Console.WriteLine(" The data has been boxed !");
             }
             // We change here i Value of 
             i = 33;
             Console.WriteLine("int i The current value is :{0}",i);
            Console.WriteLine("int i The boxed value is :{0}",obj);
        }
     }

(2) Unpacking:


 int i = 10;
     object obj = i;
     int j = (int)obj;  
     ( 3 ) to avoid frequent packing: 
     int i = 10;
     int j = 20;
     int s = 30;
     Console.WriteLine("i The value of is {0} , j The value of is {1} , s The value of is {2}", i.ToString(), j.ToString(), s.ToString());

The above is an introduction to the packing and unpacking of C #. The idea is clear and the contents involved are comprehensive, including the advantages and disadvantages of packing and unpacking, the steps of packing and unpacking, etc. It is very suitable for beginners to learn.


Related articles: