Analysis and comparison of several common containers

Source: Internet
Author: User

1. List, Vector, Deque and ArrayList, LinkedList

STL provides three of the most basic containers: Vector,list,deque

Vector and built-in arrays are similar, that is, the bottom layer is the array data structure, thread synchronization, but now is replaced by ArrayList, has been rarely used. It has a contiguous memory space, and the starting address is the same, so it can be very well supported immediately access, that is, the [] operator, but because its memory space is continuous, so in the middle of the insert and delete will cause a copy of the memory block, in addition, when the array of memory space is not enough, You need to reapply a large enough memory and make a copy of the memory. These have greatly affected the efficiency of vectors. For simple small objects, vectors are more efficient than list. Vector expands the capacity by twice times each time it expands, which is very efficient for small objects.

List in the data structure is expressed as a linear table, the list of objects in the set emissions in a certain order, the contents can be repeated, because the collection system has an index,list<e> set inherited from Collection<e> is an interface, the list interface implements the class: ArrayList (Implementing dynamic arrays), vectors (implementing dynamic arrays), LinkedList (Implementing a linked list), stack (implementation stack).

Deque is a double-ended queue, its concrete implementation is not very clear, but know that it has the following two features:

It supports the [] operator, which is then accessible, and is comparable to the efficiency of the vector.

It supports operations at both ends: Push_back,push_front,pop_back,pop_front and so on, and the efficiency of the list on both sides of the operation is similar.

In Summary:
Vector applies: Small number of objects change, simple objects, random access elements frequently
List applies: the number of objects varies greatly, objects are complex, insertions and deletions are frequent
The biggest difference is , the list is bidirectional, and the vector is one-way.

Therefore, in the actual use, how to choose which of the three containers, should be based on your needs, should generally follow the following principles:
1. If you need efficient immediate access, without the efficiency of insert and delete, use vector
2, if you need a large number of insertions and deletions, and do not care about the immediate access, you should use the list
3, if you need to immediately access, and care about the end of data insertion and deletion, you should use Deque.

The ArrayList is used as an array to hold objects. Features: Fast query, but the deletion is slightly slower, the thread is out of sync.

Using an array to place objects in a contiguous position, when adding objects to the collection, the size of the array changes as well, so it has the advantage of fast random access, even though the performance problems of accessing each element are small, but the disadvantage is that it is slow to add or remove objects. When you create an array that is not sure of its capacity, so when we change this array we have to do a lot of processing in memory, if you want to add an object in the middle of any of the two elements in the array, then in the in-memory array to move all subsequent objects.

LinkedList the underlying use of a linked list data structure. Features: Deletion speed quickly, query slightly slow.

It is through the connection of the node to implement the data structure of the linked list, the speed of inserting or deleting elements into LinkedList is very fast, and the speed of random access is relatively slow, this is due to the nature of the linked list itself, in the list, each node contains a reference to the previous node, After a node's reference and node storage values, when a new node is inserted, only the relevant front and back relationship node references need to be modified, and the node is deleted as well. The operand only needs to change the link of the node, and the new node can be stored anywhere in the memory, but also because of this linkedlist although there is a get () method, but this method by traversing the node to locate so slow. LinkedList also has a separate addfrist (), AddLast (), Getfrist (), GetLast (), Removefirst (), Removelast () methods that enable LinkedList to act as a stack, a queue , and dual queues to use.

2, ArrayList object list of the two kinds of traversal way:

public class Arraylisttraversal {
public static void Main (string[] args) {
arraylist<string> list = new arraylist<string> ();
List.add ("A");
List.add ("B");
List.add ("C");
List.add ("D");
System.out.println ("... The first traversal method: foreach traversal ... ");
for (Object li:list) {
System.out.println (LI);
}
System.out.println ("... The second way of traversal: Listiterator iterate ... ");
Listiterator<string> it = List.listiterator ();
while (It.hasnext ()) {
Object obj = It.next ();
System.out.println (obj);
}
}
}

........ The first type of traversal: foreach traversal ...
A
B
C
D
........ The second way of traversal: Listiterator iterative traversal ...
A
B
C
D

3. Use LinkedList to simulate a stack or queue data structure.

That is: stack: Advanced out; queue: FIFO first.

public class Linkedlisttraversal {
Private linkedlist<object> link;
Linkedlisttraversal () {
link = new linkedlist<object> ();
}
public void Myadd (Object obj) {
Link.addfirst (obj);
}
Public Object MyGet () {
return Link.removefirst ();//Advanced---to change to first-in, Removefirst () to Removelast ()
}
public Boolean isNull () {
return Link.isempty ();
}
public static void Main (string[] args) {
Linkedlisttraversal dl = new Linkedlisttraversal ();
Dl.myadd ("Hello1");
Dl.myadd ("Hello2");
Dl.myadd ("Hello3");
Dl.myadd ("Hello4");
while (!dl.isnull ()) {
System.out.println (Dl.myget ());
}
}
}

Advanced Post-out:

Hello4
Hello3
Hello2
Hello1

4, about ArrayList

(1) Features: ArrayList (dynamic array) is the complex version of the array, the dynamic increase and decrease of elements, the implementation of the ICollection and IList interfaces, the flexibility to set the size of the array.

(2) Usage scenario: The most common usage of ArrayList

One situation:

ArrayList List = new ArrayList ();

for (int i=0;i<10;i++) {

List.add (i); }//Add 10 int elements to the array

List.removeat (3);//Remove the 4th element
for (int i=0;i<3;i++) {

List.add (I+30);

}//Add 3 more elements

Int32[] values = (int32[]) List.toarray (typeof (Int32));//Returns an array containing the ArrayList, copied into a new array

Similar to int32[] values = new Int32[list.count]; List.copyto (values);

Another scenario:
ArrayList List = new ArrayList ();
List.add ("string");
List.add (1);//Add different types of elements to the array
Object[] values = List.toarray (typeof (object)); That's right
String[] values = (string[]) List.toarray (typeof (String)); Error
The array is different because it can be converted toObjectarrays, it is not an error to add different types of elements to the ArrayList, but when calling the ArrayList method, either pass the type or object type that all elements can be correctly transformed, or you will throw an exception that cannot be transformed.
5. Differences betweenArrayList and array arrays, and ArrayList efficiency issues
(1) ArrayList is a complex version of array
ArrayList internally encapsulates an array of type Object, which, in general terms, has no intrinsic difference, and even ArrayList many methods, such as index, INDEXOF, Contains, Sort is the corresponding method of calling array directly on the basis of an internal array.
(2) The effect of the internal object type
For general reference types, this part of the impact is not very large, but for value types, adding and modifying elements inside the ArrayList will result in boxing and unpacking operations, and frequent operations may affect some of the efficiency. But for most people, most applications use arrays of value types. There is no way to eliminate this effect, unless you do not use it, you will have to take part of the efficiency loss, but this part of the loss will not be very large.
(3) Array expansion
This is a factor that has a great influence on the efficiency of ArrayList. Whenever a method of adding elements, such as Add, AddRange, Insert, Insertrange, is checked, the capacity of the internal array is not sufficient, and if it is, it will reconstruct an array at twice times the current capacity, copy the old elements into the new array, and discard the old array. At this point in the expansion operation, it should be compared to the impact of efficiency.
Example 1: For example, a data that may have 200 elements is dynamically added to a ArrayList created with the default 16 element size, will pass through: 16*2*2*2*2 = 2,564 times the expansion will meet the final requirements, then if you start with: ArrayList List = New ArrayList (210), the way to create ArrayList, not only reduces the array creation and copy operations, but also reduces memory usage.
Example 2:30 elements are expected to create a arraylist:arraylist List = new ArrayList (30);
In the execution process, added 31 elements, then the array will be expanded to 60 elements of the size, and this time there will be no new elements added, and there is no call to the Trimsize method, then there is 1 expansion of the operation, and wasted 29 element size space. If this is the case, use: ArrayList List = new ArrayList (40); then everything is settled. Therefore, it is an important way to improve the efficiency of ArrayList use to correctly estimate the possible elements and call the Trimsize method when appropriate.
(4) Frequent calls to IndexOf, contains and other methods (Sort, BinarySearch and other methods optimized, not excluded) caused by the loss of efficiency
First, let's make it clear that ArrayList is a dynamic array that does not include algorithms that are accessed quickly through key or value, so actually calling IndexOf, contains, and so on is a simple loop that executes to find the element, So frequent calls to such methods are not faster than writing loops yourself and optimizing them, and if so, we recommend using a collection of key-value pairs such as Hashtable or SortedList.
ArrayList al=new ArrayList ();

Al. ADD ("how");
Al. ADD ("is");
Al. ADD ("you!");

Al. ADD (100);
Al. ADD (200);
Al. ADD (300);

Al. ADD (1.2);
Al. ADD (22.8);

.........

The first method of traversing a ArrayList object
foreach (Object o in AL)
{
Console.Write (o.tostring () + "");
}

The second way of traversing ArrayList objects
IEnumerator Ie=al. GetEnumerator ();
while (ie. MoveNext ())
{
Console.Write (ie. Curret.tostring () + "");
}

The third method of traversing ArrayList objects
UseArrayListAn attribute of the object that returns the number of elements in this object.
Then, using the index 
for (int i=0;i<count;i++)
{
Console.Write (Al[i]. ToString () + "");
}

Analysis and comparison of several common containers

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.