Suggestions for writing high-quality code to improve C # programs: Generic collections, Selection collections, and collections security

Source: Internet
Author: User
Tags foreach arrays garbage collection readline sleep thread

Objective

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.

This article has been updated to http://www.cnblogs.com/aehyok/p/3624579.html. This article mainly studies the following contents:

Recommendation 20, using generic collections instead of non-generic collections

Recommendation 21, select the correct collection

Recommendation 22, ensuring the linear security of the set

Recommendation 20, using generic collections instead of non-generic collections

Http://www.cnblogs.com/aehyok/p/3384637.html Here's an article that I've been dedicated to introducing generics. We should try to use generic collections. Because generics do have its benefits:

1. Provides type safety and can check for errors during compilation

2, more importantly, in most cases, the performance of a generic collection is much higher than that of a non-generic collection.

Let's take a look at a simple test performance code:

Class Program {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 ();///again garbage collection of all code, mainly including objects from the finalizer queue Collectioncount = GC.
            Collectioncount (0);///returns the number of garbage collections performed in the 0 generation watch = new stopwatch (); Watch.
        Start (); } static void Testend () {watch.
            Stop (); Console.WriteLine ("Time consuming: {0}", watch.)
            Elapsedmilliseconds.tostring ()); Console.WriteLine ("Garbage collection times: {0}", GC.
        Collectioncount (0)-collectioncount);
            static void Testarraylist () {ArrayList ArrayList = new ArrayList ();
            int temp = 0;
                for (int i = 0; i < Testcount i++) {arraylist.add (i); temp = (int) ARRaylist[i];
        } arrayList = null;
            static void Testgenericlist () {list<int> List = new list<int> ();
            int temp = 0; for (int i = 0; i < Testcount; i++) {list.
                ADD (i);
            temp = List[i];
        } list = null;
            static void Main (string[] args) {Console.WriteLine ("Start Test ArrayList");
            Testbegin ();
            Testarraylist ();
            Testend ();
            Console.WriteLine ("Start Test list<t>");
            Testbegin ();
            Testgenericlist ();
            Testend ();
        Console.ReadLine (); }
    }

Implementation results are as follows

The number of times I tested above was 10000000, and it was found that both of them were relatively large in both garbage collection times and time-consuming, so generics collections have an advantage over non-generic collections. So try to use a generic collection in our program.

Recommendation 21, select the correct collection

http://www.cnblogs.com/aehyok/p/3643928.html Here's a blog I just wrote about the collection, which is a brief introduction to some of the more frequently used collections.

If the number of sets is fixed and does not involve transformation, using an array is highly efficient, otherwise it is using list<t>.

Like using arrays, ArrayList, list<t>, dictionary<key,value> These collections are a bit more efficient at inserting and deleting data, and the disadvantage is that the search efficiency is relatively low.

About queues can refer to Http://msdn.microsoft.com/zh-cn/library/System.Collections.Queue (v=vs.80). aspx

About stacks you can refer to Http://msdn.microsoft.com/zh-cn/library/System.Collections.Stack (v=vs.110). aspx

Recommendation 22, ensuring the linear security of the set

As mentioned in recommendation 18, one of the reasons a foreach loop cannot replace a for loop is to remove and delete the collection itself during the iteration. Porting this scenario to a multithreaded scenario is the focus of this recommendation: ensuring the thread safety of the collection. Collection thread safety is the need to keep synchronization between threads when adding live deletion elements on multiple threads.

Let's take a look at it in more detail with an example and simply define an entity class

 public class Person {public string Name {get; set;} public int Age {get; set;}} 
 static list<person> List = new list<person> () {new person () {name= "Aehyok", age=25
        The new person () {name= "Kris", age=23}, the new person () {name= "Leo", age=26}};
        static AutoResetEvent AutoSet = new AutoResetEvent (false); static void Main (string[] args) {thread T1 = new Thread (() => {///block   
                Current thread autoset.waitone (); foreach (var item in list) {Console.WriteLine ("T1:" +item.)
                    Name);
                Thread.Sleep (1000);
            }
            }); T1.
   
            Start ();
                Thread t2 = new Thread (() => {///notification T1 can execute code autoset.set ();
                Thread.Sleep (1000); List.
            RemoveAt (2);
            }); T2.
   
            Start ();
        Console.ReadLine (); }

The simple analysis of this code, in fact, is to define a list set, and then define a autorestevent instance, used to control the thread.

Next, two threads are defined in the main function, the thread is paused in the online Cheng, and then the thread is notified to continue running when the call line Cheng. Final Run Results

This article URL address: http://www.bianceng.cn/Programming/csharp/201410/45473.htm

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.