Skip to content

last() method for LinkedList can be more efficient#1456

Closed
davydotcom wants to merge 1 commit intoapache:GROOVY_2_5_Xfrom
davydotcom:patch-2
Closed

last() method for LinkedList can be more efficient#1456
davydotcom wants to merge 1 commit intoapache:GROOVY_2_5_Xfrom
davydotcom:patch-2

Conversation

@davydotcom
Copy link
Copy Markdown
Contributor

A LinkedList has a method called getLast() which on a DoublyLinkedList is a direct reference. Using size and get() can take more overhead in testing. While this optimization is VERY small, it can have impacts on large list traversals

@daniellansun
Copy link
Copy Markdown
Contributor

+1

@eric-milles
Copy link
Copy Markdown
Member

Isn't this true for any implementer of java.util.Deque?

@eric-milles
Copy link
Copy Markdown
Member

The actual implementation for get(int i) in LinkedList starts from head or tail:

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    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;
        }
    }

So last(List) is not O(n) if that was the perception.

@paulk-asert
Copy link
Copy Markdown
Contributor

Merged. I also tweaked to make it for Deque as per Eric's suggestion. As noted by Eric, this may yield almost no benefit for LinkedList but can't be worse and may be significantly better for some Deque implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants