Writing high-quality code to improve the 157 suggestions for C # programs [dynamic array, loop traversal, object set initialization]

Source: Internet
Author: User

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.

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

We recommend that you do not use arrays when the number of elements is variable.

17. Use foreach for loop traversal in most cases

It is recommended that foreach cannot replace

19. Use more effective objects and set Initialization

In C #, once an array is created, its length cannot be changed. If we need a dynamic and variable-length set, we should use ArrayList or List <T> to create it. The array itself, especially the one-dimensional array, will be specially optimized to improve its efficiency when encountering an algorithm that requires high efficiency. One-dimensional arrays also become vectors, and their performance is optimal. Special commands are used in IL to process them.

From the perspective of memory usage, arrays have the following features:

1. An array is allocated with a fixed length of memory during creation.

2. If the array element is of the value type, the length of each element is equal to the length of the corresponding value type.

3. If the array element is of the reference type, the length of each element is the IntPtr. Size of the reference type.

4. Once the storage structure of the array is allocated, it cannot be changed.

ArryaList is like this:

1. ArrayList is a linked list structure that can dynamically increase or decrease memory space.

2. If ArrayList stores values, it adds 12 bytes of space for each element. Four bytes are used for object reference, and eight bytes are the object headers introduced during element packing.

List <T> is the generic Implementation of ArrayList, which saves the overhead of unpacking and packing.

To dynamically change the length of an array, convert the array to ArrayList or List, as shown in the following code:

                        [] iArr = { ,,,,,,            ArrayList arrayListInt =            List<> listInt = iArr.ToList<>);

Another method is to use the array copy function. The Array inherits from System. Array. The abstract class System. Array provides some useful implementation methods, including the Copy method, which is responsible for copying the content of an Array to another Array. Regardless of the method, changing the array length is equivalent to re-creating an array object.

To make the array look like it has the function of dynamically changing the length, you can also create an extension method named ReSize.

        Array ReSize( Array array,==, newArray, 

The call method is as follows:

          Main([] iArr = { ,,,,,,= ([])ClassForExtensions.ReSize(iArr, 

Next we will compare the performance, first look at the Code:

      Main(  [] iArr = {,,,,,=             iArr = ([])iArr.ReSize(            Console.WriteLine(  <> iArr =  List<>( [] { , , , , , , = 

The Main function mainly calls the two methods defined by myself. The first is to reset the length of the array, and the second is to set the length of the List <T>, which is measured by running time:

Strictly speaking, the List <T> does not have a statement about changing the length. Here, we will mainly compare it, set the length of the List <T>, and assign a value. Even so, in terms of time efficiency, ResizeList is much higher than ResizeArray.

I have just written an article about how to use foreach to traverse a set. If you are interested, read it. Http://www.cnblogs.com/aehyok/p/3641193.html

I feel that using foreach for loop traversal has three advantages in total:

1. Provides simple and concise syntax.

2. automatically add the code to the try-finally block.

3. If the type implements the IDispose interface, foreach will automatically call the Dispose method after the loop ends.

Foreach has the following problem: it does not support adding or deleting collections during loops. Let's take a look at a simple example:

            List<> list =  List<>() { , , , ,  ( item 

Let's take a look at the execution results:

Next we will try it using:

            List<> list =  List<>() { , , , ,  ( i = ; i < list.Count(); i++

It is certainly okay to delete it. But let's take a closer look. For example, when it deletes index 0 for the first time, that is, it deletes 1, it will immediately re-adjust the index and then delete the index for the second time, delete 3 instead of 2. There are two items remaining after the final operation

The foreach loop uses the iterator to traverse the set. It maintains a set version control in the iterator provided by FCL. So what is the set version? Simply put, it is actually an integer variable. any addition or deletion operation on the set will add 1 to the version number. The foreach loop calls the MoveNext method to traverse elements. The MoveNext method detects the version number. Once the version number is changed, an InvalidOperationException is thrown.

If the for loop is used, this problem will not occur. For directly uses the cited tool, which does not judge the set version number, so there is no exception caused by changes to the Set (except for the case where the index length is exceeded ).

Index. Due to version detection, the foreach loop does not carry the for loop.

You can assign values to automatically implemented attributes directly in braces for object initialization settings.

      Name { ;   Age { ;   Main(=  Person() { Name = , Age = 

In the past, only the constructor method can be used to pass in values, or assign values to attributes after the object is constructed. Now these steps are simplified. The initialization setting is actually equivalent to the compiler assigning values to attributes after the object is generated.

      Name { ;   Age { ;   Main(=  Person() { Name = , Age = <Person> personList =  List<Person> Person() { Name = , Age = 

Using the set initialization settings, the compiler calls the Add method for the set after the set object is created. The code above demonstrates how to create a new object or an existing object and a null value in the initialization statement.

However, the initialization setting is not only for the convenience of object and set initialization, but also for the initialization of attributes for the anonymous type in the LINQ query. Because all anonymous attributes in the collection returned by the LINQ query are read-only, if you need to assign values to an anonymous attribute or add an attribute, you can only initialize the setting items. The initialization setting can also use expressions for attributes.

Let's look at a piece of code:

List<Person> lst =  List<Person> Person(){ Age = ,Name= Person(){ Age = ,Name= entity =  p   { p.Name, AgeScope = p.Age >  ?  :  ( item .Format(

The Agoda attribute is calculated. With such a convenient initialization method, the code is more elegant and flexible.

 

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.