The difference between vectors, ArrayList, and LinkedList in Java __java

Source: Internet
Author: User
Tags wrapper
the difference between vectors, ArrayList, and LinkedList in Java

The difference between vectors, ArrayList, and LinkedList in Java

The SDK provides several implementations of an ordered set interface Java.util.List, three of which are known to be vectors, ArrayList, and LinkedList. The performance difference for these list classes is a frequently asked question. In this article, I'm going to explore the difference in performance between LinkedList and Vector/arraylist.

To fully analyze the performance differences between these classes, we must know how they are implemented. So, I'll start with a performance perspective, and briefly introduce the implementation features of these classes.

I. The realization of vector and ArrayList
Both vectors and ArrayList are provided with an underlying object[] array, which is used to hold the elements. When you access an element through an index, you simply access the elements of the internal array through the index:
Public Object get (int index)
{//First check whether the index is legal ... This part of the code is not shown here return
Elementdata[index]; }

An internal array can be greater than the number of elements owned by the Vector/arraylist object, and the difference between the two is the remaining space for the new element to be quickly added. With the rest of the space, adding elements becomes very simple, simply by saving the new element to an empty location in the internal array and then adding the index value for the new free position:
Public boolean Add (Object o)
{ensurecapacity (size + 1);///later elementdata[size++] = O; return true;
List.add (Object) return value}


Inserting an element into any specified position in the collection (rather than the end of the collection) is slightly more complicated: all array elements above the insertion point must move one position forward before they can be assigned:
public void Add (int index, Object element) {
First check whether the index is legal ... This part of the code is not shown here
Ensurecapacity (size+1);
System.arraycopy (Elementdata, index, Elementdata, index + 1,
Size-index);
Elementdata[index] = element;
size++;
}


When the remaining space is used up, if additional elements need to be added, the Vector/arraylist object must replace its internal object[] array with a larger new array, copying all the array elements to the new array. Depending on the SDK version, the new array is 50% or 100% larger than the original (the code shown below expands the array by 100%):
public void ensurecapacity (int mincapacity) {
int oldcapacity = Elementdata.length;
if (Mincapacity > Oldcapacity) {
Object olddata[] = elementdata;
int newcapacity = Math.max (oldcapacity * 2, mincapacity);
Elementdata = new Object[newcapacity];
System.arraycopy (olddata, 0, elementdata, 0, size);
}
}


The main difference between a vector class and a ArrayList class is synchronization. In addition to the two methods used for serialization only, no ArrayList method has the ability to perform synchronously, whereas most methods of vectors have synchronous capabilities, either directly or indirectly. Therefore, vector is thread safe, but ArrayList is not. This makes the ArrayList faster than the vector. For some of the latest JVMs, the speed difference between the two classes can be negligible: strictly speaking, for these JVMs, the difference in speed for these two classes is less than the time difference shown by the tests that compare these classes of performance.

The vector and ArrayList implementations have excellent performance when accessing and updating elements through the index, because there is no overhead other than scope checking. Unless the internal array space is depleted and must be extended, there is also excellent performance when you add elements to the end of the list or delete elements from the end of the list. Inserting and deleting elements is always an array copy (two copies are required when the array must be expanded first). The number of copied elements is proportional to [size-index], which is proportional to the distance between the insertion/deletion point and the last index position in the collection. For inserts, the worst performance is when the element is inserted at the top of the collection (index 0), which is best when inserted at the end of the collection (after the last existing element). As the collection scale increases, the overhead of array replication increases rapidly, as the number of elements that must be replicated for each insert operation increases.

Ii. the realization of LinkedList
LinkedList is implemented through a doubly linked list of nodes. To access an element through an index, you must find all nodes until you find the target node:
Public Object Get (intindex) {
First check whether the index is legal ... This part of the code is not shown here
Entry e = header; Start node
Look forward or backward, in which direction the distance is more
Near decision
if (Index < SIZE/2) {
for (int i = 0; I <= index; i++)
e = E.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}


Inserting an element into a list is simple: Locate the node for the specified index, and then insert a new node immediately before the node:
public void Add (int index, Object element) {
First check whether the index is legal ... This part of the code is not shown here
Entry e = header; Starting node
Look forward or backward, in which direction the distance is more
Near decision
if (Index < SIZE/2) {
for (int i = 0; I <= index; i++)
e = E.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
Entry newentry = new Entry (element, E, e.previous);
NewEntry.previous.next = Newentry;
newEntry.next.previous = Newentry;
size++;
}


Thread-safe linkedlist and other collections
If you want to get a thread-safe linkedlist from the Java SDK, you can use a sync wrapper to get one from Collections.synchronizedlist (List). However, using a synchronous wrapper is equivalent to adding an indirect layer, which can have expensive performance costs. When the wrapper passes the call to the encapsulated method, each method needs to add an additional method call, and the method encapsulated by the synchronized wrapper can be two to three times times slower than the encapsulated method. The overhead of this indirect invocation is not significant for complex operations like search, but this overhead can have a significant impact on performance for simpler methods, such as access or update functionality.

This means that, compared to vectors, the linkedlist of a synchronized package is significantly inferior in performance because the vector does not require any additional indirect calls for thread safety. If you want to have a thread-safe linkedlist, you can copy the LinkedList class and have several necessary methods synchronized so that you can get a faster implementation. This is equally valid for all other collection classes: Only the list and map have an efficient thread-safe implementation (vector and Hashtable classes, respectively). Interestingly, these two efficient thread-safe classes exist for backward compatibility only, not for performance reasons.

The performance overhead of LinkedList implementations is slightly greater for indexing access and updating of elements, because accessing either index requires spanning multiple nodes. When inserting an element, there is another cost, in addition to the performance overhead spanning multiple nodes, that is, the overhead of creating a Node object. In the area of advantage, there is no additional overhead for the INSERT and delete operations implemented by the LinkedList, so the insertion-deletion overhead is almost entirely dependent on the insertion-deletion point from the end of the collection.


ArrayList and vectors typically have better performance than the LinkedList after LinkedList and synchronous encapsulation. Even if you think LinkedList may provide higher performance, you can also get better performance from ArrayList by modifying the way elements are added, such as flipping the order of elements in the collection.

In some cases linkedlist will have better performance, for example, when a large number of elements need to be added to the beginning and end of a large collection at the same time. In general, however, I recommend that you use the Arraylist/vector class as a priority, using LinkedList only if there are obvious performance problems and LinkedList can improve performance.

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.