1. Unpacking and packing, we all know
Boxing: Converting a value type to a reference type
Unboxing: Converting a reference type to a value type
2. Take a look at the following example:
String str= "123"
int N=convert.toint32 (str);
String is a reference type and int is a value type. So, is there a unboxing here?
The answer is: no
Cause: Look at whether the two types have occurred boxing or unpacking, to see whether there is an inheritance relationship between the two types. It's possible to have an inheritance relationship.
Occurrence of crating and unpacking
3, now, we only know the definition of the Disassembly box, then unboxing to the end of our application to bring advantages or disadvantages?
We can look at the following code:
class program {static VO ID Main (string[] args) {//int n = 10; Object o = n;//boxed//n = (int) o;//unboxing ArrayList list = new ArrayList (); Stopwatch SW = new Stopwatch (); Sw. Start (); for (int i = 0; i < 10000000; i++) {list. ADD (i);//Boxing 10 million times approx. 1.477} SW. Stop (); Console.WriteLine (SW. Elapsed); Console.readkey (); list<int> list = new list<int> (); Stopwatch SW = new Stopwatch (); Sw. Start (); for (int i = 0; i < 10000000; i++)//{//list. ADD (i);//No boxing, spents 0.12 seconds//}//SW. Stop (); Console.WriteLine (SW. Elapsed); Console.readkey (); } }
We know that the list collection is of type object type, so that each time the int type data is added, the boxing operation is performed, and the list<int> generic collection type is int, and the int type data is added without boxing
By running the results we can see that the addition of the list collection to the same data is significantly longer than the list<> generic collection.
Therefore, the unboxing operation will affect (reduce) the speed of our application, so in the development should try to avoid the unboxing operation!
Unpacking and boxing