Java Stack vs Queue performance
Solution 1
The java.util.Stack class is deprecated. Use a Deque instead.
As far as performance, that depends on the implementation,
Solution 2
Stack and Vector are both synchronized. Use java.util.ArrayDeque as both Stack and Queue instead, see API:
This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.
Solution 3
Performance depends on what data structure you going to use (arraylist, linkedlist etc) and what all operations you will be performing.
So depending on that you can decide your data structure. Will suggest you to go through Java API to know pluses and minuses of different API.
Solution 4
It depends on usage patterns and the specific implementation.
In general:
- Use a queue if you want to process a stream of incoming items in the order that they are received (first-in-first-out or FIFO). Good for work lists and handling requests.
- Use a stack if you want to push and pop from the top of the stack only (last-in-first-out or LIFO). Good for recursive algorithms.
P.S. I wouldn't recommend using any of the old implementation that extend or utilise java.util.Vector
. There are many much better implementations available nowadays, depending on your exact use case.
Fricken Hamster
Updated on June 09, 2022Comments
-
Fricken Hamster almost 2 years
So I have a list that can be in either a stack or queue. Is there any performance difference between the two?
Also I notice the java.utils implementation extends Vector. Would it be faster to make my own implementation, or maybe just directly use a Vector?
-
user207421 over 11 yearsWithout referring to a specific implementation the question is meaningless.
-
drum over 11 yearsThe most obvious answer I can give you is queue performs better in FIFO and stack performs better in FILO.
-
Fricken Hamster over 11 yearsJust the default java.utils implementation I mentioned in the question. I can take from first or last.
-
user207421 over 11 yearsYou didn't mention any default implementation of the queue.
-
Louis Wasserman over 11 years
ArrayDeque
is probably simpler and faster than either.
-
-
user207421 over 11 yearsIt is not deprecated. -1.
-
Thomas Jungblut over 11 yearsIt is not deprecated, but it is not recommended to use it anymore as stated in the javadocs
A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.
. -
Thorn G over 11 yearsI should have phrased that differently -- it is not officially deprecated, but like
Vector
its use is not recommended in modern Java programs.