In order to facilitate the development of the article, first introduced the boxing (Boxing) and unpacking (unboxing) these two nouns. NET type is divided into two types, one is the value type and the other is the reference type. The essential difference between the two types is that the value type data is allocated on the stack, and the reference type data is allocated on the heap. So if you want to put a value type data on the heap, you need boxing operations, or, conversely, put a value type on the heap to remove the data, you need to do a unboxing operation.
For example, for the following simple boxing and unboxing operation statements.
int i = 123;
object obj = i;//Boxing
if( obj is int )
int j = (int) obj;//Unboxing
In order to better illustrate the boxing and unboxing operations, I borrowed the MSDN explanations for "Boxing", as detailed below.
Understand the meaning of these two names, now talk about why to reduce boxing and unboxing operations.
There are two reasons for this, mainly on efficiency: one is the low operating efficiency of the heap, and the other is that for memory resources allocated on the heap, GC is required to recycle, which reduces program efficiency.
With these two factors in mind, you need to reduce the boxing and unboxing operations in your program.
How to reduce it, involves the more of these two operations, the format of the output operation, such as: String.Format, Console.WriteLine, such as statements.
For example:
Console.WriteLine ("Number List:{0}, {1}, {2}", 1,2,3);
For "1,2,3", the equivalent of the previous "123", need to be boxed and unboxing two operations. So how to avoid, in fact, as long as the WriteLine Pass reference type data, that is, according to the following way.
Console.WriteLine ("Number List:{0}, {1}, {2}", 1.ToString (), 2.ToString (), 3.ToString ());
Because the result of "1.ToString ()" is a string type, it belongs to a reference type and is therefore not involved in boxing and unboxing operations.
Second, there are a lot of boxing and unboxing operations in the collection, such as: ArrayList or Hashtable.