Why is LinkedList slower than ArrayList when added to the end of a list?

I read THIS and

And I realized that LinkedList add (E element) is O (1) and ArrayList add (E element) is O (1) amortized, but O (n) is the worst since the array needs to be modified and copied

But when I try to check it out

public class ArrayListVSLinkeedList {

public ArrayListVSLinkeedList() {

    final int COUNTER = 15000000;

    List<Integer> arrayList = new ArrayList<Integer>();

    long tStart_add = System.currentTimeMillis();

    for (int i = 0; i < COUNTER; i++) {
         arrayList.add(i);
    }
    long tEnd_add = System.currentTimeMillis();
    long tDelta_add = tEnd_add - tStart_add;
    System.out.println("Adding to ArrayList: " +tDelta_add);


    List<Integer> linkedList = new LinkedList<Integer>();
    tStart_add = System.currentTimeMillis();
    for (int i = 0; i < COUNTER; i++) {
        linkedList.add(i);
    }
    tEnd_add = System.currentTimeMillis();
    tDelta_add = tEnd_add - tStart_add;
    System.out.println("Adding to LinkedList: " +tDelta_add);
}

public static void main(String[] args) {
    new ArrayListVSLinkeedList();
}
}

I got the output:

Adding to ArrayList: 9122

LinkedList Addendum: 19859

I know this is not a real benchmark, but ... Finally, adding an element to the end of an ArrayList is faster than a LinkedList. Why is this happening?

+4
source share
2 answers

- .

ArrayList.add:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

An ArrayList , , . ensureCapacityInternal , .

, . ( - btw - O (1)).

, , . . , , - O (n). , - ( ) .

, LinkedList.add:

public boolean add(E e) {
    linkLast(e);
    return true;
}

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++;
}

, node, . , O (1), node , .

+5

, , , , ArrayList , LinkedList . .

- .

0

All Articles