Linkedhashset source code analysis and performance optimization
Linkedhashset is a collection in Java, which inherits from HashSet and implements the SET interface.Compared with Hashset, Linkedhashset can retain the order of the insertion of elements and has a faster traversal performance.This article will analyze the source code of LinkedhashSet and provide some suggestions for performance optimization.
The internal implementation of Linkedhashset is based on HashMap and LinkedList.It uses HashMap to achieve fast search for elements, and use LinkedList to maintain the order of the element.Therefore, the performance of adding and deleting elements in Linkedhashset is very efficient, with an average time complexity of O (1).
The following is the main source code analysis of Linkedhashset:
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable {
private transient LinkedHashMap<E, Object> map;
// Construction method
public LinkedHashSet() {
map = new LinkedHashMap<>();
}
// Add elements
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
// Delete elements
public boolean remove(Object o) {
return map.remove(o) == PRESENT;
}
// Traversing elements
public Iterator<E> iterator() {
return map.keySet().iterator();
}
// ...
}
It can be seen from the source code that Linkedhashset is actually achieved by maintaining a HashMap.HashMap's key storage actual element, which is a fixed Object object.And Linkedhashset only cares about the order of the key, not concerned.
When using Linkedhashset, you need to pay attention to the following points of performance optimization suggestions:
1. Consider the specified initial capacity during initialization: LinkedhashSet uses HashMap internally. If the approximate size of the set is known in advance, you can improve the performance by specifying the initial capacity by initialization.
LinkedHashSet<Integer> set = new LinkedHashSet<>(10000);
2. Try to avoid frequent expansion: LinkedhashSet needs to re -calculate the hash value when expanding capacity, and re -assign memory and other operations, which will affect performance.Therefore, in the case of a large number of known set elements, the initial capacity can be avoided by reasonable setting.
LinkedHashSet<Integer> set = new LinkedHashSet<>(10000);
set.add(1);
set.add(2);
// ...
3. Avoid a large number of element delete and insert operation: Linkedhashset has good performance on insertion and delete operations, but if a large number of element is required to delete and insert operations, it is recommended to consider other data structures, such as ArrayList or LinkedList.
In general, Linkedhashset is a collection of good performance and retaining the insertion order.When using, you can choose the appropriate initial capacity according to the actual situation, avoid frequent expansion operations, and pay attention to avoid a large number of element delete and insert operation to obtain better performance.