Writing high-quality code to improve C # programs-replacing non-generic sets with generic sets (20 is recommended ),

Source: Internet
Author: User

Writing high-quality code to improve C # programs-replacing non-generic sets with generic sets (20 is recommended ),

Collections are inevitable during software development. collections in C # are represented by arrays and several collection classes. Both arrays and collection classes have their respective advantages and disadvantages. How to use a set is a skill we must master in the development process. Don't underestimate these skills. Once an incorrect set or method for the set is used in development, the application will run away from your expectation.

Recommendation 20: Use a generic set instead of a non-generic set

In recommendation 1, we know that to make code run efficiently, we should avoid packing and unpacking as much as possible, and minimize transformation. Unfortunately, this is not done in the first generation set type provided by Microsoft. Let's take a look at the usage of the ArrayList class:

  ArrayList al=new ArrayList();      al.Add(0);      al.Add(1);      al.Add("mike");      foreach (var item in al)      {        Console.WriteLine(item);      }

The code above fully demonstrates how bad we can write the program.

First, the Add method of ArrayList accepts an object parameter, so al. add (1) is first packed. Secondly, in the foreach loop, the box is split again when it is traversed.

In this Code, the integer and string as the value type and reference type are implicitly forced to be converted into an object, and then transformed back in the foreach loop.

At the same time, this code is non-type secure: ArrayList stores both integer and string types, but does not have the type check during compilation. Although it is sometimes necessary to implement it like this, we should avoid it as much as possible in more cases. If the type check is missing, an implicit Bug occurs during running. If the ArrayList of the Collection class performs the following operations, an IvalidCastException will be thrown:

 ArrayList al=new ArrayList();      al.Add(0);      al.Add(1);      al.Add("mike");      int t = 0;      foreach (int item in al)      {        t += item;      }

ArrayList also providesICollectionThe parameter constructor can directly receive arrays, as shown below:

var intArr = new int[] {0, 1, 2, 3};ArrayList al=new ArrayList(intArr);

The internal implementation of this method is as bad as follows (the following InsertRange method is finally called in the constructor ):

public virtual void InsertRange(int index, ICollection c){  if (c == null)  {    throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));  }  if ((index < 0) || (index > this._size))  {    throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));  }  int count = c.Count;  if (count > 0)  {    this.EnsureCapacity(this._size + count);    if (index < this._size)    {      Array.Copy(this._items, index, this._items, index + count, this._size - index);    }    object[] array = new object[count];    c.CopyTo(array, 0);    array.CopyTo(this._items, index);    this._size += count;    this._version++;  }}

To sum up, if you perform circular access, transformation, or packing and unpacking for large sets, using a traditional set like ArrayList will have a great impact on efficiency. In view of this, Microsoft provides support for generics. The wildcard uses a pair of <> parentheses to enclose the actual type, and then the compiler and runtime will complete the remaining work. Microsoft does not recommend that you use the ArrayList type. Instead, you are recommended to use their generic implementation, such as List <T>.

Note that the non-Generic set is in the System. Collections namespace, and the corresponding Generic set is in the System. Collections. Generic namespace.

We recommend that you implement the generic Implementation of the code at the beginning as follows:

List<int> intList = new List<int>();      intList.Add(1);      intList.Add(2);      //intList.Add("mike");      foreach (var item in intList)      {        Console.WriteLine(item);      }

The line commented in the code will not be compiled, because "mike" is not an integer, which reflects the characteristics of type security.

The following compares the running efficiency of non-generic sets and generic sets:

Static void Main (string [] args) {Console. writeLine ("Start test ArrayList:"); TestBegin (); TestArrayList (); TestEnd (); Console. writeLine ("Start test List <T>:"); TestBegin (); TestGenericList (); TestEnd ();} static int collectionCount = 0; static Stopwatch watch = null; static int testCount = 10000000; static void TestBegin () {GC. collect (); // force garbage collection of all codes in real time. waitForPendingFinalizers (); // suspends the thread and executes the GC of the terminator (the destructor) in the terminator queue. collect (); // garbage collection of all code again, mainly including the object collectionCount = GC from the terminator queue. collectionCount (0); // returns the number of garbage collection times executed in code 0. watch = new Stopwatch (); watch. start ();} static void TestEnd () {watch. stop (); Console. writeLine ("Time consumed:" + watch. elapsedMilliseconds. toString (); Console. writeLine ("garbage collection times:" + (GC. collectionCount (0)-collectionCount);} static void TestArrayList () {ArrayList al = new ArrayList (); int temp = 0; for (int I = 0; I <testCount; I ++) {al. add (I); temp = (int) al [I];} al = null;} static void TestGenericList () {List <int> listT = new List <int> (); int temp = 0; for (int I = 0; I <testCount; I ++) {listT. add (I); temp = listT [I];} listT = null ;}

Output:

Start to test ArrayList:

Duration: 2375

Garbage collection times: 26

Start test List <T>:

Duration: 220

Garbage collection times: 5

The preceding section describes how to write high-quality code to improve C # programs-use a generic set instead of a non-generic set (20 is recommended). Suggestions for writing high-quality code 1 to 157 are recommended, this document will be updated continuously. Please pay attention to it. Thank you.

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.