Why are array lists faster than a linked list for LIFO behavior?

I wrote an algorithm that has many additions and deletions of elements to the end of the data structure (basically the last in the first).

Now, for some reason, when I perform this operation with ArrayList, it is much faster than LinkedListeven moving overhead is required through ArrayList. It is even a little faster. It is millions faster!

Why is this?

+4
source share
3 answers

, , LinkedList, . ArrayList, , . , , . , LinkedList .

+6

remove - O (n-index) ArrayList, O (1), , O (n) LinkedList.

-2

LinkedList , . , .

Inserting into an ArrayList is a little more expensive if the number of elements in the ArraList already has the size of the class array. This will mean that he will have to create a new array and copy the elements. In addition, it has direct access to the last element, which makes it very easy to add and remove elements.

PS you can also consider using the stack. Not sure about your requirements, but just like a sentence.

-2
source

Source: https://habr.com/ru/post/1583890/


All Articles