Valid tive C # item17: Minimize boxing and unboxing

Source: Internet
Author: User

Valid tive C # item17: Minimize boxing and unboxing

There are two types of values and references in. net, they are inconsistent .. Net Framework uses packing and unpacking as a bridge between the two. You can encapsulate a value type into a non-type reference object through packing. In case of unpacking, the reference type is released from the package. When we need to treat the value type as a reference type, packing and unpacking are necessary. However, such operations will waste additional resources. In general, temporary object copies will also be created during packing and unpacking, which may pose a hidden risk to our programs. We should minimize the number of packing and unpacking operations.

Packing can change a value type to a reference type, which is allocated to the stack. This box contains a copy of the boxed value type and Its Implementation interfaces. When we need to restore it, we will create a corresponding value type and assign it to the copy in the box.

Packing and unpacking automatically happen, which is exactly where they are dangerous. When we use a value type as a reference type, the compiler automatically performs these conversions. In addition, when we use the interface to operate the value type, it will also cause packing and unpacking. There is no warning when it occurs. In the following example, packing occurs:

Console. writeline ("a few numbers: {0}, {1}, {2}", 25, 32, 50 );

The parameters of the overloaded console. writeline are referenced in a group. For the int type, you must first bind it to the writeline method. In addition, writeline calls the tostring () method of the boxed object. In this way, our code is actually similar to the following:

First, packing:

Int I = 25;
Object o = I;
Console. writeline (O. tostring ());

When unpacking:

Object O;
Int I = (INT) O;
String output = I. tostring ();

We should not allow the compiler to perform such conversions automatically. The compiler's intention is good. It automatically generates the necessary packing and unpacking code to help us compile the code. To avoid this, we can convert our type to string before writeline:

Console. writeline ("a few numbers: {0}, {1}, {2}", 25. tostring (), 32. tostring (), 50. tostring ());

This can avoid conversion. Such a simple example tells us that we should always pay attention to such conversions. If possible, we should try to avoid automatic conversion.

Another issue that we may encounter when automatically converting the value type to the reference type is the set in. Net 1. X. In. Net 1.x, The system. object instance is centrally stored. Boixng occurs when we add a value type to it. When we use these storage instances, the returned copy of the value type in the boxed object is not the value type itself. This may cause some potential bugs:

Public struct person
{
Private string name;
Public string name
{
Get
{
Return name;
}
Set
{
Name = value;
}


}
Public override string tostring ()
{
Return name;
}
}
// Try to modify
Arraylist list = new arraylist ();
Person P = new person ();
P. Name = "";
List. Add (P );

Person P2 = (person) list [0];
P2.name = "B ";

Console. writeline (list [0]. tostring ());

The modification will not succeed. Person is a value type. It is packed before it is stored in arraylist. When we use it later, a copy is returned. We cannot modify the object in the set.

From this point, we can see that we should declare the value type as immutable. If we really need variable value types, we can use system. array to achieve our goal.

If the array is not a suitable set, we can use the interface method to achieve the goal. Through the interface, we can modify the value type value in the box:

Public interface ipersonname
{
String name
{
Get;
Set;
}
}

Public struct person: ipersonname
{
Private string name;
Public string name
{
Get
{
Return name;
}
Set
{
Name = value;
}


}
Public override string tostring ()
{
Return name;
}
}

Through the interface, we access the original object instead of copying the original object. In this way, we can modify the value type value in the set.

Arraylist list = new arraylist ();
Person P = new person ();
P. Name = "";
List. Add (P );
(Ipersonname) list [0]). Name = "B ";
Console. writeline (list [0]. tostring ());

Many restrictions in C #2.0 have been improved, but we should try to avoid them once. Frequent packing and unpacking not only wastes system resources, but also reduces program execution efficiency and may cause unexpected bugs. Do not use it whenever possible.

Translated from Objective C #: 50 specific ways to improve your C # by Bill Wagner

PS: there is an article on msdn about packing and unboxing which introduces how to use the packing class to reduce this conversion.

Http://www.microsoft.com/china/msdn/Archives/voices/csharp03152001.asp

Back to directory

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.