Writing high-quality code to improve C # programs--using generic collections instead of Non-generic collections (recommended) _mssql

Source: Internet
Author: User
Tags garbage collection

In software development, collections are inevitably used, and collections in C # represent arrays and several collection classes. Whether they are arrays or collection classes, they have their own pros and cons. How to use a good collection is a skill we must master in the development process. Do not underestimate these techniques, and once you have used the wrong set or approach to the collection in development, the application will run away from your expectations.

Recommendation 20: Use generic collections instead of non-generic collections

As we know in recommendation 1, if you want your code to work efficiently, you should try to avoid boxing and unboxing, as well as minimizing transitions. Unfortunately, we did not do this in the first-generation collection type that Microsoft provided to us, and here we look at the use of this class ArrayList:

  ArrayList al=new ArrayList ();
      Al. ADD (0);
      Al. ADD (1);
      Al. ADD ("Mike");
      foreach (var item in AL)
      {
        Console.WriteLine (item);
      }

The above code demonstrates how poorly we can write the program.

First, the ArrayList Add method accepts an object argument, so al. ADD (1) completes the boxing first, and second, in the Foreach Loop, the unboxing is completed once it is traversed.

In this code, both the shaping and the string as value types and reference types are implicitly coerced into object and then transformed back into the Foreach loop.

Also, this code is not type safe: We arraylist both the integer and the string, but the compile-time type checking is missing. Although sometimes it is necessary to do so deliberately, but more often, should try to avoid. Type checking is missing, which can cause hidden bugs at run time. Collection Class ArrayList If you perform the operation shown below, a ivalidcastexception is 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 provides a construction method with ICollection parameters that can receive arrays directly, as follows:

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

The method is as bad as the internal implementation, as shown below (the following Insertrange method is finally called inside the constructor):

public virtual void Insertrange (int index, ICollection c)
{
  if (c = = null)
  {
    throw new argumentnullexcept Ion ("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++
  }
}

In general, traditional collections such as ArrayList can have a significant impact on efficiency if you iterate over large collections, transform them, or box and remove them. In view of this, Microsoft provides support for generics. Generics enclose the actual type using a pair of <> brackets, and then the compiler and runtime complete the remaining work. Microsoft also does not recommend using types such as ArrayList, and instead recommends using their generic implementations, such as list<t>.

Note that a Non-generic collection is under the System.Collections namespace, and the corresponding generic collection is under the System.Collections.Generic namespace.

The generic implementation of the proposed code for the first time is:

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 that is annotated in the code is not compiled because "Mike" is not an integral type, and here is the characteristic of type safety.

The following compares the efficiency of a non-generic collection and a generic collection in operation:

 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 (); Enforces an instant garbage collection GC for all code. WaitForPendingFinalizers (); Suspends the thread and executes the finalizer (that is, the destructor) GC in the finalizer queue.  Collect (); All code is garbage collected again, mainly including objects from the Terminator queue Collectioncount = GC.  Collectioncount (0);
      Returns the number of garbage collections performed in 0 code watch = new Stopwatch (); Watch.
    Start (); } static void Testend () {watch.
      Stop (); Console.WriteLine ("Time consuming:" + 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; }

The output is:

Start Test ArrayList:

Time Consuming: 2375

Number of garbage collection: 26

Start testing list<t>:

Time consuming: 220

Number of garbage collection: 5

The above describes writing high quality code to improve C # programs--using generic collections instead of Non-generic collections (recommendation 20), about writing high quality code Recommendations 1 to recommendation 157, this complete will continue to update, please pay attention, 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.