157 recommendations for writing high-quality code to improve C # programs--recommendation 16: Arrays should not be used in cases where the number of elements is variable

Source: Internet
Author: User

Recommendation 16: Arrays should not be used in cases where the number of elements is variable

In C #, once an array is created, the length cannot be changed. If we need a dynamic and variable-length collection, we should create it using ArrayList or list<t>. The array itself, especially a one-dimensional array, is specifically optimized to improve its efficiency when it encounters an algorithm that requires high efficiency. A one-dimensional array is also a vector, and its performance is optimal, and special instructions are used in IL to process them (such as Newarr, Ldelem, Ldelema, Ldelen, and Stelem).

In terms of memory usage, arrays are allocated a fixed length of memory when they are created. If the element of the array is a value type, the length of each element is equal to the length of the corresponding value type, and if the element of the array is a reference type, the length of each element is intptr.size of that reference type (Intptr:it's a class that wraps a pointer that is used when calling Windows API functions. The underlying pointer may be a + bit or a-bit, depending on the platform. Once the storage structure of an array is allocated, it can no longer change. ArrayList is a linked list structure that dynamically increases or decreases memory space, and if ArrayList stores value types, it adds 12 bytes of space to each element, where 4 bytes have an object reference and 8 bytes are the object headers introduced when the element is boxed. List<t> is a generic implementation of ArrayList, which eliminates the overhead of boxing and unpacking.

Attention:

Because of the memory characteristics of the array itself, the problem of large objects should also be noted in the process of using arrays. The so-called "big object" refers to those objects that account for more than 85000 bytes of memory, which are allocated in the large object heap. The allocation and collection of large objects are not the same as small objects, especially for recycling, and large objects are inefficient in the process of recycling. Therefore, it is not possible to specify an oversized length for an array, which makes the arrays a large object.

If you must dynamically change the length of an array, one way is to convert the array to ArrayList or LIST<T>, as the following code says:

 int  [] Iarr = {0 , 1 , 2 , 3 , 4 , 5 , 6             };   ArrayList arraylistint  = new  ArrayList (Iarr); //  Arraylistint.add (7  
    
     ); List 
     <int  > Listint = iarr.tolist<             int  > (); //  listint.add (7 ); 
    

Another way is to copy the array function. The array inherits from the System.Array, and the abstract class System.Array provides some useful implementation methods. This includes the Copy method, which is responsible for copying the contents of an array into another array. Either way, changing the length of the array is equivalent to recreating an array object.

In order for the array to appear to have the ability to dynamically change the length, you can create an extension method named resize, as shown in the following code:

     Public Static class classforextensions    {        publicstatic Array ReSize (thisint  newSize)        {            = array. GetType (). GetElementType ();             = array.createinstance (t, newSize);             0 0 , Math.min (array. Length, NewSize));             return newarray;        }    }

The calling method looks like this:

int 0 1 2 3 4 5 6  = (int[]) iarr.resize (N);

Here's a comparison of the time-consuming changes to the length of the array and the change of the lisit<t> length to emphasize the topic of this recommendation: arrays should not be used when the number of elements is variable.

        Private Static voidResizearray () {int[] Iarr = {0,1,2,3,4,5,6 }; Stopwatch Watch=NewStopwatch (); Watch.            Start (); Iarr= (int[]) Iarr.resize (Ten); Watch.            Stop (); Console.WriteLine ("Resizearray:"+Watch.        Elapsed); }        Private Static voidresizelist () {List<int> Iarr =Newlist<int> (New int[] {0,1,2,3,4,5,6 }); Stopwatch Watch=NewStopwatch (); Watch.            Start (); Iarr.add (0); Iarr.add (0); Iarr.add (0); Watch.            Stop (); Console.WriteLine ("resizelist:"+Watch.        Elapsed); }

The output is:

resizearray:00:00:00.0004441

resizelist:00:00:0:0000036

Of course, strictly speaking,,list<t> does not exist to change the length of the argument, this recommendation is only for comparison, the length of the Iarr to 10, but also the assignment. Even so, we can see that in time efficiency resizelist is 100 times times higher than Resizearray.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--recommendation 16: Arrays should not be used in cases where the number of elements is variable

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.