Packing and Unpacking

Preface
Unboxing and boxing are the conversion of value types and reference types. Boxing is the conversion of value types to reference types, generally to System.Object types or interface reference types implemented by value types; unboxing is the conversion of reference types to values. Type, the reference type here can only be a boxed reference type object.

Value types and reference types
CLR supports two types: reference types and value types; CLR is a JVM-like existence, a runtime environment, responsible for garbage collection of memory allocation, etc.
The following pictures can clearly show the type classification:
write picture description here

Examples of boxing and unboxing The above three lines of code complete the process of boxing and unboxing. We can clearly find that int→Object boxing: object o = x; //boxing Object→int unboxing: int y = (int) o; //unboxing

int x = 1023;
object o = x; //装箱
int y = (int) o; //拆箱



How about the performance of boxing and unboxing
Generally speaking, boxing has a higher performance overhead, because the allocation of reference objects is more complicated and expensive, and the value type is allocated on the stack, and the efficiency of allocation and release is very high. The boxing process needs to create a new reference object instance, and the unboxing process needs to create a value type field, which has lower overhead.

Summary
Boxing is a value type, and only value types can be boxed. The boxed reference object after unboxing and unboxing is a reference object instance with a value type field. The box is stored on the heap, and only the value Types only have two states of boxing and unboxing, and reference types are always in the box.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325846039&siteId=291194637