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

查看:25
本文介绍了在 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天全站免登陆