问题描述
我目前使用 List<T> 作为队列(使用
p>lst[0]
然后 lst.removeAt(0)
) 来容纳对象.在给定时间最多大约有 20 个项目.我意识到有一个实际的 Queue<T>
类.我想知道使用 Queue<T>
而不是像队列一样的 List<T>
是否有任何好处(性能、内存等)?
I'm currently using a List<T>
as a queue (use lst[0]
then lst.removeAt(0)
) to hold objects. There's about 20 items max at a given time. I realized there was an actual Queue<T>
class. I'm wondering if there's any benefit (performance, memory, etc.) to using a Queue<T>
over a List<T>
acting like a queue?
推荐答案
可以分析性能.尽管在这种项目很少的情况下,您可能需要运行代码数百万次才能真正获得有价值的差异.
Performance can be profiled. Though in this case of so few items, you may need to run the code millions of times to actually get worthwhile differences.
我会这样说:Queue<T>
会更明确地暴露你的 intent,人们知道队列是如何工作的.
I will say this: Queue<T>
will expose your intent more explicitly, people know how a queue works.
像队列一样使用的列表不是很清楚,尤其是当您有很多不必要的索引和 RemoveAt(magicNumber)
代码时.从代码维护的角度来看,Dequeue
更具消耗性.
A list being used like a queue is not as clear, especially if you have a lot of needless indexing and RemoveAt(magicNumber)
code. Dequeue
is a lot more consumable from a code maintenance point of view.
如果这会给您带来可衡量的性能问题,您可以解决它.不要预先解决所有潜在性能问题.
If this then gives you measurable performance issues, you can address it. Don't address every potential performance issue upfront.
这篇关于队列<T>vs列表<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!