Note: During the packing process, a new heap (managed heap) object will be generated, and its value type value will be copied to the reference type (heap object). After that, the value type variable does not affect the reference type. When unpacking, a new stack type variable is generated, copying the value of the reference type to the value type (stack object), and then changing the new value type, it does not affect the original reference type.
1. packing and unpacking are an abstract concept.
2. binning converts the value type to the reference type. The binning function converts the reference type to the value type, you can convert any value of the allowed value type to the value of the object type to link the value type with the reference type, for example, int val = 100; object OBJ = val; console. writeline ("object value = {0}", OBJ); this is a packing process, which is the process of converting the value type to the reference type int val = 100; object OBJ = val; int num = (INT) OBJ; console. writeline ("Num: {0}", num); this is a box-breaking process that converts the value type to the reference type and then from the reference type to the value type. Note: only objects that have been packed in boxes can be split.
3 ,. in. net, the data type is divided into value type and reference (not the same as the pointer of C ++) type. Correspondingly, the memory allocation is divided into two methods: Stack, second, heap. Note: it is a managed heap. The value type is only allocated in the stack. Allocate memory and managed heap for reference types. The managed heap corresponds to garbage collection.
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.
5: Why is packing required? (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 the data.
6: binning/unboxing internal operations. Packing: assign an object instance to the heap and copy the value to the new object. Step by step. 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. Someone understands this: If int32 is packed, the returned address points to an int32. I don't think it can be understood in this way, but this is indeed a problem. It is incomplete, and int32 does not speak about its essence (in the managed heap ). Unpacking: 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. In the book, unpacking only gets the pointer to the value type in the referenced object, and copying the content is triggered by the value assignment statement. I think it doesn't matter. The most important thing is to check the nature of the object instance, and The binning and packing types must match. On this point, on the Il layer, I cannot see the principle. I guess, maybe a method like GetType is called to retrieve the type for matching (because strict matching is required ).
7: The effect of packing/unpacking on execution efficiency is obvious. From the principle, we can see that during packing, a brand new reference object is generated, which may cause time loss, that is, the efficiency is reduced. 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 how to 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.
8: a better understanding of packing/unpacking is not as simple and clear as described above. For example, when packing, it becomes a reference object, a method table pointer will be provided, what will this do? We can further explore through examples. For example. Struct a: icloneable {public int32 X; Public override string tostring () {return string. format ("{0}", x) ;}public object clone () {return memberwiseclone () ;}} static void main () {A;. X = 100; console. writeline (. tostring (); console. writeline (. getType (); a A2 = (a). clone (); icloneable c = a2; ojbect o = C. clone ();} 5.0:. tostring (). The compiler finds that a overrides the tostring method and directly calls the tostring command. Because a is a value type, the compiler does not show polymorphism. Therefore, it is called directly without packing. (Note: tostring is the base class system of. valuetype method) 5.1:. getType (), GetType is inherited from system. to call the valuetype method, a method table pointer is required. Therefore, a is boxed to generate a method table pointer and call the System of the base class. valuetype. (ADD, all value types are inherited from system. valuetype ). 5.2: A. Clone (). Because a implements the clone method, no packing is required. 5.3: icloneable Transformation: When A2 is converted to the interface type, it must be packed because the interface is a reference type. 5.4: C. Clone (). You do not need to pack it. Call the packed objects in the previous step in the managed stack. Note: in fact, the above is based on a fundamental principle. Because the unboxed value type does not have a method table pointer, you cannot use the value type to call the inherited virtual method on it. In addition, the interface type is a reference type. In my understanding, the table pointer of this method is similar to the virtual function table pointer of C ++. It is an important basis for implementing the polymorphism mechanism of referenced objects.
9: how to change a boxed object to a boxed object. Because the specified method cannot be called directly, you must unpack the object before calling the method, but unpack the object again, A new stack instance is generated, and the packing object cannot be modified. A little dizzy. I feel like I'm talking about tongue twisters. For example: (append the change method in the preceding example) Public void change (int32 X) {This. X = x;} call: A = new A ();. X = 100; object o = A; // bind it to O. below, you want to change the O value. (A) O). Change (200); // has it been changed? Not changed. The reason for not changing is that O generates a temporary stack instance a when unpacking. Therefore, the change is based on temporary A and has not been changed to the packing object. (Appendix: In managed C ++, you can directly change the instance reference obtained in step 1 when directly taking and disassembling the box, but C # does not work .) So how should we be good? Well, the same effect can be achieved through the interface method. Implementation: interface ichange {void change (int32 X);} struct a: ichange {... } Call: (ichange) O). Change (200); // has it been changed? Get rid of it. Why can I change it now? When converting o to ichange, it will not be packed again here. Of course, it will not be split, because o is already of the reference type, and because it is of the ichange type, you can directly call change, therefore, the fields in the boxed object are changed to achieve the expected effect.
10. ------------------------ to convert a value type to a reference type, you need to perform the boxing operation (boxing): 1. First, allocate memory for the newly generated reference object from the managed heap. 2. copy the data of the value type to the allocated memory. 3. Return the address of the newly allocated object in the managed heap. It can be seen that the memory allocation and data copy operations affect the performance during a packing operation. To convert a referenced inner type to a value inner type, you need to perform the unboxing operation (unboxing): 1. First, obtain the address of the field that belongs to the value type in the hosting heap, this step is strictly case-removing. 2. Copy the value in the reference object to the value type instance on the thread stack. After these two steps, it can be considered that the same boxing is an inverse operation. In a strict sense, unpacking does not affect the performance, but the subsequent data copying operations will affect the performance as in boxing operations.
11. ------------------------- all types of net are composed of the base class system. object Inheritance, including the most common basic types: int, byte, short, bool, etc., that is, all things are objects. If you declare that these types of memory are allocated in heap, it will cause extremely low efficiency! (The medium reason and the difference between stack and stack will be discussed separately in another article !) How does. net solve this problem? By dividing a type into values and regerencetype ), the value types defined in C # include sbyte, byte, short, ushort, Int, uint, long, ulong, Char, float, double, bool, and decimal), enumeration (Enum), structure (struct), reference types include: Class, array, interface, Delegate, String, etc. The value type is used to allocate memory in the stack. It is initialized at the same time as the Declaration to ensure that the data is not null. The reference type is used to allocate memory in the heap and the initialization is null, the reference type requires the garbage collection to recycle the memory. The value type is not used. If the reference type is out of the scope, the system will automatically release it! The following is the definition of packing and unpacking! Packing is to implicitly convert a value type to a reference object. For example: int I = 0; syste. Object OBJ = I; this process is packed! It is to pack I! Unpacking is to convert a referenced object into any value type! For example, int I = 0; system. Object OBJ = I; Int J = (INT) OBJ; in this process, the first two sentences are to pack I, and the last sentence is to unpack obj.