. NET Framework source code Research Series-vest list

Source: Internet
Author: User

In the previous article <. in the Net Framework source code Research Series --- delegate>, we studied it together.. net. today we will study it together. net.

As you all know. in the. NET collection class, the List, such as array, is an ordered one-dimensional array. Unlike array, we can more easily operate a list-type set, such as inserting data, deleting data, and sorting, so. net source code, how is list implemented? Will there be other costs when we use the advantages of list over array? What can we learn from the source code of list? With these questions, let's start today's. net source code research journey.

First, let's take a look at the list type definition. Through the Object Browser, we can easily know that list inherits the implementation of ilist, ienumerator, icollection and Other interfaces.. Net in this way:

Public class List<T>:Ilist<T>, system. Collections.Ilist

This is different from what we see in the Object Browser, because the ilist interface also inherits fromIenumerator, icollection interface.

Next, let's take a look at the fields and constructors in the list:

Code

  Public     Class  List  <  T  >  : Ilist  <  T >  , System. Collections. ilist {
Private Const Int _ Defacapcapacity = 4 ;
Private T [] _ items;
Private Int _ Size;
Private Int _ Version;
[Nonserialized]
Private Object _ syncroot;
Static T [] _ emptyarray = New T [ 0 ];
Public List (){
_ Items = _ Emptyarray;
}
Public List ( Int Capacity ){
If (Capacity < 0 ) Throwhelper. throwargumentoutofrangeexception (exceptionargument. Capacity, exceptionresource. argumentoutofrange_smallcapacity );
_ Items = New T [capacity];
}
Public List (ienumerable < T > Collection ){
If (Collection = Null )
Throwhelper. throwargumentnullexception (exceptionargument. Collection );

Icollection < T > C = Collection As Icollection < T > ;
If (C ! = Null ){
Int Count = C. count;
_ Items = New T [count];
C. copyto (_ items, 0 );
_ Size = Count;
}
Else {
_ Size = 0 ;
_ Items = New T [_ defacapcapacity];

Using (Ienumerator < T > En = Collection. getenumerator ()){
While (EN. movenext ()){
Add (EN. Current );
}
}
}
}

Note the third constructor of list.CodeWe can find that the original list uses an array to store data.. Here we can think that list is only a layer-packed array, and we can conclude that the List performance is definitely not as good as array (packaging will often lead to performance loss ).

Then let's take a look at several fields in the list. from private const int _ defaultcapacity = 4; we can see that list can contain at least four elements by default. the _ size field is the current length of the list. access list. the capacity attribute is used to obtain the number of elements that a list can contain. access list. the Count attribute can be used to obtain the number of elements currently contained in the list. so what are their differences? After careful research, we found that the original implementation of list self-growth is like this. when an element is added, the list first determines the length of _ size and _ items. If they are equal, the size is extended to _ SIZE + 1 to _ items. length * 2. for details, see the following source code:

Code

 Public     Void  Add (T item ){
If (_ Size = _ Items. Length) ensurecapacity (_ size + 1 );
_ Items [_ size ++ ] = Item;
_ Version ++ ;
}
Private Void Ensurecapacity ( Int Min ){
If (_ Items. Length < Min ){
Int Newcapacity = _ Items. Length = 0 ? _ Defacapcapacity: _ items. Length * 2 ;
If (Newcapacity < Min) newcapacity = Min;
Capacity = Newcapacity;
}
}
Public Int Capacity {
Get { Return _ Items. length ;}
Set {
If (Value ! = _ Items. Length ){
If (Value < _ SIZE ){
Throwhelper. throwargumentoutofrangeexception (exceptionargument. Value, exceptionresource. argumentoutofrange_smallcapacity );
}
If (Value > 0 ){
T [] newitems = New T [value];
If (_ Size > 0 ){
Array. Copy (_ items, 0 , Newitems, 0 , _ Size );
}
_ Items = Newitems;
}
Else {
_ Items = _ Emptyarray;
}
}
}
}

The above code can be used to understand the principle of List Auto-growth,In the worst case, inserting an element may result in copying all the previous elements to the new array.The resulting performance problems are evident.

Looking at the code above, we will find that when copying an array, the list does not do it by itself, but calls array. copy this method. traversing the implementation code of the entire list, we found that almost all data operations in the list, such as insertion, deletion, query, sorting, and retrieval, are implemented through the corresponding static methods in the array. from this we can see what I said above"List is a layer encapsulation of array."Is correct.

We know that list inherits the icollection interface. We can see that the icollection. issynchronized attribute directly returns false.List is not thread-safe(Attention should be paid to the use of multithreading, which is different from Queue ).

In. net, we can use two methods to traverse an array, one for loop, and the other is foreach. the difference between the two is that one is sequential traversal, and the other has nothing to do with the sequence .. net supports both array and list traversal. people who have learned the iteration mode in the design mode are familiar with "traversal unrelated to sequence. the iteration mode is defined:

Provides a way to traverse and access each element in an aggregate object without exposing the internal representation of the object.

 

That's right! List is. net comes with an iterator. strictly speaking, this is because List implements the ienumerator interface. that is to say. net is an iterator that implements the ienumerator interface. do you feel very happy with the design patterns that People unconsciously embrace at work ?! :)

At the end of the Code, it is found that the list also provides the reverse () method for storing all elements in inverted storage. The implementation of this method completely copies the array. reverse, so far I have to feel that Microsoft has achieved the ultimate in code reuse. it was also found that such a powerful thing (array) was lost in the past.

Finally, let's look at the methods available in both lists (it's not easy to copy the array ):

 

Code

    Public    Void  Trimexcess (){
Int Threshold = ( Int )((( Double ) _ Items. length) * 0.9 );
If (_ Size < Threshold ){
Capacity = _ Size;
}
}
Public Bool Trueforall (Predicate < T > Match ){
If (Match = Null ){
Throwhelper. throwargumentnullexception (exceptionargument. Match );
}
For ( Int I = 0 ; I < _ Size; I ++ ){
If ( ! Match (_ items [I]) {
Return False ;
}
}
Return True ;
}

In the two methods, trueforall is used to determine whether all the elements in the list meet the specified conditions. trimexcess is used to remove the extra space added when the List itself grows. The effect is shown in the following sample code.

 

 

Code

  List  <  Int  >  Test1  =     New  List  <  Int  >  (  New    Int  [] {  0  ,  1  ,  2  ,  4  });
Console. writeline ( " The actual length of the set is {0} " , Test1.capacity );
Test1.add ( 5 );
Console. writeline ( " The actual length of the set is {0} " , Test1.capacity );
Test1.trimexcess ();
Console. writeline ( " The actual length of the set is {0} " , Test1.capacity );

Running effect:

 

 

Summary:

Today, we have studied how the. NET Framework implements the list and discovered the problems that may arise when using the list. For some of the features of the List itself, please refer to the tutorial for a better understanding of the list. 

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.