When to use the Stack collection in C#?

后端 未结 12 2262
滥情空心
滥情空心 2021-02-14 20:44

I do understand how Stack() and Stack works, but I really can\'t see any scenarios where an array, List or IEnumer

12条回答
  •  难免孤独
    2021-02-14 20:49

    Stack and Queue use internally an array. If you were using arrays in smart ways the chances are good that you have used them in a stack or queue like fashion already. Usually you need to decide between Stack and Queue. A typical example where a Stack is needed is depth first search. If you change the collection to a queue you have implemented a breadth first search.

    Another example is heavy multithreading where you pass data between a producer and consumer via a stack if the processing order is not relevant. The rationale behind this is that if much data is going to be processed it is better for the CPU to use the latest added data chunk for further processing on the other thread to get better cache locality.

    And the list goes on ....

提交回复
热议问题