Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is ArrayDeque faster than stack?

Tags:

According to javadoc,

ArrayDeque class is likely to be faster than Stack when used as a stack

I don't understand how can ArrayDeque be faster than stack. Suppose stack is implemented using linkedlist as follows:

Push: Insert new element at the head, teamp->next = head; head = temp 
(where temp is the element to be inserted)
Pop: Remove the element from head, and make head = head->next

For large number of elements, there will be a overhead for ArrayDeque to resize which won't be a case in Stack implemented using LinkedList. So how exactly is ArrayDeque faster than stack?

like image 332
Gaurav Avatar asked May 28 '14 10:05

Gaurav


People also ask

Why ArrayDeque is faster than LinkedList and stack?

Time complexity for ArrayDeque for accessing a element is O(1) and that for LinkList is is O(N) to access last element. ArrayDeque is not thread safe so manually synchronization is necessary so that you can access it through multiple threads and so they they are faster.

Is ArrayDeque better than stack?

The ArrayDeque class implements the Deque interface In fact, the Java API documentation even states that the ArrayDeque class will often times be faster than a Queue or a Stack. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.

Which is faster LinkedList or stack?

If you want to search or access a specific element, arrays are faster, but if you want to insert or delete an element, a linked list is faster.

Is ArrayDeque a queue or stack?

An ArrayDeque (also known as an “Array Double Ended Queue”, pronounced as “ArrayDeck”) is a special kind of a growable array that allows us to add or remove an element from both sides. An ArrayDeque implementation can be used as a Stack (Last-In-First-Out) or a Queue(First-In-First-Out).


2 Answers

ArrayDeque is part of the Java Collections Framework and is not written to be inherently thread safe.

Stack, together with Vector and Hashtable came with Java 1.0 and were implemented with thread safe operations (because it seemed like a good idea at the time). Acquiring and releasing thread locks is relatively expensive time wise, hence those data structures will be much slower than their compatriots in the JCF.

like image 83
Steve C Avatar answered Sep 23 '22 03:09

Steve C


Because most operations don't require the array to resize, particularly once the queue has reached a stable size and isn't growing any more.

Every time you add an item Stack has to allocate new objects update the links, etc.

ArrayDeque just needs to put an object in the array and update an index.

like image 24
Tim B Avatar answered Sep 20 '22 03:09

Tim B