ArticleDirectory
- What is packing and unpacking?
What is packing and unpacking?
Packing refers to converting a value type to a reference type or a value type (such as a structure) to implement any interface type.When the CLR loads the value type, the value is encapsulated into system. object, and then stored on the managed stack. Unpacking is to extract the value type from the object orInterface Type to implement explicit conversion of the Value Type of this interface. It is invisible during packing, and the unpacking is explicit.
Packing
Value Type to the type Object or to any interface type implemented by this value type. "> packing is an implicit conversion from the value type to the reference type or any interface type implemented by this value type. binning the value type will allocate an object instance in the heap and copy the value to the new object.
The following Code is used for packing: O , on the stack, that references a value of the type int , on the heap. "> Create an object reference OBJ on the stack, and reference int type value. I . "> this value is a copy of the Value Type value assigned to the variable I .
1IntI =123;2//Value Type to reference type, boxed, implicit3ObjectOBJ = I;
Two variables are described.IAndOBJInter-packing conversion:
Unpack
The following code indicates first packing and then unpacking:
1IntI =123;2//Value Type to reference type, boxed, implicit3ObjectOBJ =I;4//Extract the value type from the reference type, Unbox, and explicitly5IntJ = (Int) OBJ;
Code Process
BinningIncluding:
Binning and unboxing PairsProgramPerformance impact
Compared with the simple assignment, the packing and unboxing process requires a lot of calculations. When packing value types, a new object must be allocated and constructed. OtherwiseThe forced conversion required for unpacking also requires a large amount of computing. Therefore, we should try to reduce the number of packing and unpacking operations in the program.
References & further reading
Packing and unboxing
Value Type
Reference Type