Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest Java collection with the basic functionality of a Queue?

What is the fastest collection in Java?

I only need the operations to add and remove, order is not important, equals elements is not a issue, nothing more than add and remove is imporant.

Without limit size is important too.

These collection will have Objects inside him.

Currently I'm using ArrayDeque because I see this is the faster Queue implementation.

like image 930
Renato Dinhani Avatar asked May 25 '11 19:05

Renato Dinhani


People also ask

What is the best way to implement Queue in Java?

You can use . offer(E e) to append an element to the end of the queue and . poll() to dequeue and retrieve the head (first element) of the queue. Java defined the interface Queue , the LinkedList provided an implementation.

What is Queue collection in Java?

Queue in Java is a linear data structure where you can handle an ordered collection of elements. It follows the FIFO principle to add elements from one end and remove them from the other end. You have seen the methods add, offer, poll, and remove.


2 Answers

ArrayDeque is best. See this benchmark, which comes from this blog post about the results of benchmarking this. ArrayDeque doesn't have the overhead of node allocations that LinkedList does nor the overhead of shifting the array contents left on remove that ArrayList has. In the benchmark, it performs about 3x as well as LinkedList for large queues and even slightly better than ArrayList for empty queues. For best performance, you'll probably want to give it an initial capacity large enough to hold the number of elements it's likely to hold at a time to avoid many resizes.

Between ArrayList and LinkedList, it seems that it depends on the average number of total elements the queue will contain at any given time and that LinkedList beats ArrayList starting at about 10 elements.

like image 100
ColinD Avatar answered Sep 23 '22 15:09

ColinD


You can use a java.util.LinkedList - it's doubly-linked and cicrular, so adding to one end and taking from the other are O(1)

Whatever implementation you choose, refer to it by the Queue interface, so that you can easily change it if it turns out not to fit your case (if, of course, a queue is what you need in the first place)

Update: Colin's answer shows a benchmark that concludes that ArrayDeque is better. Both have O(1) operations, but LinkedList creates new objects (nodes), which slightly affect performance. Since both have O(1) I don't think it would be too wrong to choose LinkedList though.

like image 33
Bozho Avatar answered Sep 25 '22 15:09

Bozho