Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - PriorityQueue vs sorted LinkedList

Which implementation is less "heavy": PriorityQueue or a sorted LinkedList (using a Comparator)?

I want to have all the items sorted. The insertion will be very frequent and ocasionally I will have to run all the list to make some operations.

like image 695
rasgo Avatar asked May 20 '10 21:05

rasgo


2 Answers

A LinkedList is the worst choice. Either use an ArrayList (or, more generally, a RandomAccess implementor), or PriorityQueue. If you do use a list, sort it only before iterating over its contents, not after every insert.

One thing to note is that the PriorityQueue iterator does not provide the elements in order; you'll actually have to remove the elements (empty the queue) to iterate over its elements in order.

like image 190
erickson Avatar answered Sep 26 '22 07:09

erickson


You should implement both and then do performance testing on actual data to see which works best in your specific circumstances.

like image 30
nohat Avatar answered Sep 22 '22 07:09

nohat