Java Stack vs Queue performance

12,432

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.

Share:
12,432
Fricken Hamster
Author by

Fricken Hamster

Updated on June 09, 2022

Comments

  • Fricken Hamster
    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
      user207421 over 11 years
      Without referring to a specific implementation the question is meaningless.
    • drum
      drum over 11 years
      The most obvious answer I can give you is queue performs better in FIFO and stack performs better in FILO.
    • Fricken Hamster
      Fricken Hamster over 11 years
      Just the default java.utils implementation I mentioned in the question. I can take from first or last.
    • user207421
      user207421 over 11 years
      You didn't mention any default implementation of the queue.
    • Louis Wasserman
      Louis Wasserman over 11 years
      ArrayDeque is probably simpler and faster than either.
  • user207421
    user207421 over 11 years
    It is not deprecated. -1.
  • Thomas Jungblut
    Thomas Jungblut over 11 years
    It 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
    Thorn G over 11 years
    I should have phrased that differently -- it is not officially deprecated, but like Vector its use is not recommended in modern Java programs.