C #: knowledge about packing and unpacking

Source: Internet
Author: User

1. packing and unpacking are an abstract concept.
2. Packing is to convert the Value TypeConvert to reference type;

Binning refers to the reference typeConvert to Value Type

  The binning and unboxing functions allow conversion between any value of the value type and the value of the Object type to link the value type with the reference type.

For example:

 val =  obj == {}

This is a packing process.ConvertProcess

 val =  obj = num = (, num); 

This is a binning process, which is a value type.Convert, And thenConvert to Value TypeProcess

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, 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?
: Stores value types in the garbage collection heap. Packing is from the value type to the object type or any interface type implemented by this value type.Implicit conversion.
Unpack: From the object type to the value type or from the interface type to the value type that implements this interfaceExplicit Conversion.

5:Why packing? (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:Packing/unpacking internal operations

  • Packing

  • Unpack

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. Effect of packing/unpacking on execution efficiency
Obviously, from the principle, we can see that during packing, a brand new reference object is generated, which may result in time loss, that is, reduced efficiency.
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 useOverload FunctionsTo avoid. In the second case, you can useGenericTo avoid.
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: better understanding of packing/unpacking
Packing/unpacking is not as simple and clear as above

For example, if it is changed to a reference object during packing, a method table pointer will be added. What is the use of this method?

We can further explore through examples.

For example:

  String.Format(”{  = ===

9: How to change packed objects
For packed objects, because the specified method cannot be called directly, you must unpack the object before calling the method. However, if you unpack the object again, a new stack instance is generated and the boxed object cannot be modified. A little dizzy. I feel like I'm talking about tongue twisters. For example: (append the change method in the above example)

 .x =

A a = = = a; ((A)o).Change(); 

(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.
The implementation is as follows:

 

((IChange)o).Change();

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 ):

It can be seen that the memory allocation and data copy operations affect the performance during a packing operation.

To convert a reference type to a value type, you need to perform the unboxing operation ):

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 inherited by the base class System. Object, 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 ),

Value Type and reference type defined in C #

The value type is used to allocate memory in the stack and initialize it at the same time as the Declaration to ensure that the data is not NULL;
The reference type allocates memory in the heap and is initialized to null. The reference type requires garbage collection to recycle the memory. If the value type is not used, the system will automatically release the memory when it exceeds the scope of the function!
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;
Repeated E. 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;
The first two sentences in this process are packing I, and the last one is unpacking obj!

Reprinted from: http://www.cnblogs.com/huashanlin/archive/2007/05/16/749359.html

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.