标签:赋值 分享图片 strong node return 实验 next int turn
结论:当数据量越来越大时,ArrayList比LinkedList快
原因:当数据量大时,ArrayList每次扩容都能得到很大的新空间,解决了前期频繁扩容的劣势,而LinkedList虽然有尾指针,但是每次add都要将对象new成一个Node(而ArrayList直接数组对应位置元素赋值)
末尾插入源码:
ArrayList:如果超出容量需要扩容,不需扩容时直接数组元素赋值
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
LinkedList:用传入的值new一个Node对象,然后尾指针指向该新的Node
public void addLast(E e) { linkLast(e); }
void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
实验对比:
public static void main(String[] argv) { LinkedList<Integer> linkedList = new LinkedList<Integer>(); ArrayList<Integer> arrayList = new ArrayList<Integer>(); Long start = System.nanoTime(); for (int i = 0; i < 100000; i++) { linkedList.addLast(i); } Long end = System.nanoTime(); System.out.println("LinkedList消耗时间:" + (end - start)); start = System.nanoTime(); for (int i = 0; i < 100000; i++) { arrayList.add(i); } end = System.nanoTime(); System.out.println("ArrayList消耗时间:" + (end - start)); }
ArrayList:性能主要在于扩容和数组复制,而当size很大时扩容影响就会减少
public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
LinkedList:性能主要在于遍历链表查找index
public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } } void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }
结论:开头插入,LinkedList比ArrayList快
结论:中间插入LinkedList比ArrayList慢
LinkedList插入数据效率不一定比ArrayList高,源码分析+实验对比
标签:赋值 分享图片 strong node return 实验 next int turn
原文地址:https://www.cnblogs.com/ming-szu/p/9533019.html