Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

just adding Integer numbers to Arraylist and Linkedlist, to the last position, why adding in arrayList is faster then the linkedlist? I compiled many many times, and adding in arraylist is faster, why?

As I know, ArrayList copies an array by 2^n+1 size. while linkedlist changes only the Node

class Test1 {

public static void main(String[] args) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    LinkedList<Integer> linkedList = new LinkedList<>();

    addToList(arrayList);
    System.out.println("-----------------");
    addToList(linkedList);

}

public static void addToList(List list) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 5_000_000; i++) {
        list.add(i);
    }
    long end = System.currentTimeMillis();
    System.out.println(end - start);

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you add to an ArrayList, you just have to store the integer in the backing array. Every once in a while, when the backing array fills up, you have to allocate a new array and copy all the old items to the new array. Given 5 million integers, you'll have to do that allocate-and-copy about 20 times (depends on the initial size of the list).

To add to a linked list, every addition requires that you:

  1. Allocate memory for and initialize a new linked list node.
  2. Link the new node to the end of the list.

All that extra work, for both the ArrayList and the LinkedList is done behind the scenes, by the add method.

The overhead for 5 million linked list node allocations and links is higher than the overhead for 5 million ArrayList insertions, even when you count the 20 or so allocate-and-copy operations that the ArrayList has to make when it fills up.

So, whereas each operation takes constant time (although in the ArrayList case it's really amortized constant time), the constant for appending to a linked list is higher than the constant for appending to an ArrayList.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...