ArrayList Vs LinkedList

前端 未结 9 685
一整个雨季
一整个雨季 2020-11-27 10:53

I was following a previous post on this that says:

For LinkedList

  • get is O(n)
  • add is O(1)
  • remove is O(n)
9条回答
  •  心在旅途
    2020-11-27 11:13

    This is a bad benchmark IMO.

    • need to repeat in loop multiple times to warm up jvm
    • need to DO something in your iterative loop or it can be optimized array
    • ArrayList resizes, which is costly. If you had constructed ArrayList as new ArrayList(500000) you would construct in one blow, and then all allocations would be quite cheap (one preallocating backed array)
    • You don't specify your memory JVM - it should be run with -xMs == -Xmx (everything preallocated) and sufficiently high that no GC is likely to be triggered
    • This benchmark doesn't cover the most unpleasant aspect of LinkedList - random access. (an iterator isn't necessarily the same thing). If you feed say 10% of the size of a large collection as a random selection of list.get you will find linkedlists are awful for grabbing anything other than the first or last element.

    For an arraylist: the jdk get is what you'd expect:

    public E get(int index) {
        RangeCheck(index);
    
        return elementData[index];
    }
    

    (basically just return the indexed array element.,

    For a linkedlist:

    public E get(int index) {
        return entry(index).element;
    }
    

    looks similar? Not quite. entry is a method not an primitive array, and look what it has to do:

    private Entry entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry e = header;
        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else {
            for (int i = size; i > index; i--)
                e = e.previous;
        }
        return e;
    }
    

    That's right, if you ask for say list.get(250000), it's gotta start at the head and repeatedly iterate through the next element. 250000 accesses or so (there's an optimization in the code where it starts at head or tail depending on which would be less accesses.)

提交回复
热议问题