在 C# 中迭代​​堆栈的最快方法堆栈、最快、迭代、方法

2023-09-07 10:07:32 作者:年轻就该狂

我觉得使用 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.

重新设计代码,这样就不需要循环了找到一个更快的循环结构.(我会推荐泛型,即使它并不重要.再次,做基准测试).

可能不必要的循环示例是当您尝试在列表中进行查找或匹配两个列表或类似列表时.如果循环需要很长时间,请查看将列表放入二叉树或哈希映射是否有意义.创建它们可能会产生初始成本,但如果重新设计代码,您可能会通过稍后进行 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.

 
精彩推荐
图片推荐