在C#中迭代堆栈的最快方法 [英] Fastest way to iterate over a stack in c#

查看:94
本文介绍了在C#中迭代堆栈的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得使用GetEnumerator()和转换IEnumerator.Current很昂贵.还有更好的建议吗?

如果它提供具有更好性能的类似功能,则我愿意使用其他数据结构.

I feel that using GetEnumerator() and casting IEnumerator.Current is expensive. Any better suggestions?

I'm open to using a different data structure if it offers similiar capabilities with better performance.

思考后:
泛型堆栈会是一个更好的主意,以便不需要强制转换吗?

After thought:
Would a generic stack be a better idea so that the cast isn't necessary?

推荐答案

您是否进行过任何基准测试,或者它们只是直觉?

Have you done any benchmarks, or are they just gut feelings?

如果您认为大部分处理时间都花在遍历堆栈上,则应该对其进行基准测试,并确保是这种情况.如果是这样,那么您有几个选择.

If you think that the majority of the processing time is spent looping through stacks you should benchmark it and make sure that that is the case. If it is, you have a few options.

  1. 重新设计代码,以便不需要循环
  2. 找到一个更快的循环结构. (即使没什么大问题,我还是会建议使用泛型.再次,进行基准测试.)

当您尝试在列表中进行查找或匹配两个列表或类似列表时,可能不需要循环的示例.如果循环需要很长时间,请查看将列表放入二叉树或哈希图是否有意义.创建它们可能会产生最初的成本,但是如果重新设计代码,则以后可以通过进行O(1)查找来获得回报.

Examples of looping that might not be necessary are when you try to do lookups in a list or match two lists or similar. If the looping takes a long time, see if it make sense to put the lists into binary trees or hash maps. There could be an initial cost of creating them, but if the code is redesigned you might get that back by having O(1) lookups later on.

这篇关于在C#中迭代堆栈的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆