STACK与传统For循环保留集合性能? [英] STACK vs Traditional For Loop in Reserving an Collection Performance?

查看:141
本文介绍了STACK与传统For循环保留集合性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string[] arrStr = new string[4] { "A","C","D","E"};

//----------------FOR-------------------------------------
for (int i = arrStr.Length - 1; i >= 0; i--)
{
    Console.WriteLine(arrStr[i]);
}
//-------------STACK--------------------------------------
Stack<string> stack = new Stack<string>(arrStr);
foreach (var item in stack)
{
    Console.WriteLine(item);
}





你能告诉我这些方法之间的区别吗?

你更喜欢哪一个,哪一个给你最好的表现作为优点和缺点。



任何答案都将不胜感激。



Could you guys please tell me the difference between these approaches ?
Which one would you prefer to and which one give you the most performance as the pros and cons.

Any answer would be appreciated.

推荐答案

在功能上它们没有区别,它们都做同样的事情。它们以相反的顺序处理数组。



你甚至可以这样做:



Functionally there is no difference in them, they both do the same thing. They process the array in reverse order.

You could even do this:

arrStr.Reverse().ForEach(s => Console.WriteLine(s));
arrStr.Reverse().ToList().ForEach(s => Console.WriteLine(s));





并再次获得相同的效果。



就性能而言,裸循环可能是最快的。然后,您将需要进行基准测试以确定哪个更快,Linq表达式或堆栈。



我假设这只是你正在做的事情的简化版本,如果你只是想打印一个更复杂的当前形式反向的字符串数组,我不会担心哪个比另一个更快,它的Console.Writeline调用很慢。在这种情况下,使用StringBuilder并附加一行更快,然后在最后将字符串生成器写入控制台。



and get the same effect again.

As far as performance goes, the bare for loop is probably going to be the fastest. Then you will have to benchmark to determine which is faster, the Linq expression or the stack.

I'm assuming that this is just a boiled down version of something you are doing that is much more complicated, in its current form if you just wanted to print a string array in reverse, I wouldn't be worried about which is faster than the other, its the Console.Writeline call that is slow. In this case, it would be quicker to use a StringBuilder and append a line, then at the end write out the string builder to the console.






实际上当你在一个数组上运行它而不是堆栈时会更快但我关心的是你在知道长度时使用数组,但是你不知道长度然后你使用堆栈。



现在,如果你想要反转数组或堆栈,那么性能会完全相同。
Hi,

Actually For would be faster when you run it on an array than stack but my concern is you use array when you know the length, but where you don't know the length then you use stack.

Now if you want to reverse the array or stack then performance would quite same.


请参阅下面的详细信息链接for and foreach: -

FOREACH Vs. FOR(C#) [ ^ ]

for和foreach循环之间的区别 [ ^ ]



foreach [ ^ ]和 [ ^ ]
Refer below link which is detailed about for and foreach:-
FOREACH Vs. FOR (C#)[^]
Difference between for and foreach loop[^]

foreach[^] and for[^]


这篇关于STACK与传统For循环保留集合性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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