[C #] packing and unpacking (sorting ),
Packing is to convert the value typeobjectType or any interface type implemented by this value type. When the CLR loads the value type, the value is encapsulated into System. Object, and then stored on the managed stack. Unboxing extracts the value type from the object. Packing is implicit; unpacking is explicit. The concept of packing and unpacking is the basis of the unified view of type system C #. Any type of value is regarded as an object.
In the following exampleiPacked and allocated to objectso.
1 static void Main (string [] args) 2 {3 var I = 123; // System. int324 5 // bind to I (implicit) 6 object obj = I; 7 8 Console. read (); 9}
Then, You can unpack the object o and assign it to the integer variable.i。
1 static void Main (string [] args) 2 {3 var I = 123; // System. int32 4 5 // pack (implicitly) 6 object obj = I; 7 8 // unpack (explicitly) obj 9 I = (int) obj; 10 11 Console. read (); 12}
Here we use the code to demonstrate the packing and unpacking operation:
1 static void Main (string [] args) 2 {3 // use string. format indicates the usage of packing. Here, 24 is used for packing 4 var formatStr = string. format ("{0} {1 }. "," I'm ", 24); 5 Console. writeLine ($ "formatStr: {formatStr}"); 6 7 var objs = new List <object> (); 8 for (int I = 0; I <5; I ++) 9 {10 // each time I is packed into objs 11 objs. add (I); 12} 13 14 Console. writeLine ("============"); 15 16 foreach (var obj in objs) 17 {18 // two object types cannot be used directly *, you need to use int for explicit box unboxing 19 Console. writeLine ($ "{obj} * {obj} = {(int) obj * (int) obj}"); 20} 21 22 Console. read (); 23}
Performance
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. The forced conversion required for unpacking also requires a large amount of calculations, but the degree is lighter. If your operation is centered on the loop, you will obviously feel performance problems.
Packing
Packing is used to store value types in the garbage collection heap. Packing is a value typeobjectType 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.
See the Declaration of the following value type variables:
var i = 123; //System.Int32
The following statementsiThe packing operation is implicitly applied:
// Pack I (implicitly) into object obj = I;
The result of this statement is to create an object reference on the stack.oAnd is referenced on the stack.intType value. This value is assigned to the variable.iA copy of the Value Type value. Two variables are described.iAndo.