声明内部或外部的foreach循环的变量:这是更快/更好? [英] Declaring a variable inside or outside an foreach loop: which is faster/better?
本文介绍了声明内部或外部的foreach循环的变量:这是更快/更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
其中哪一个是更快/更好的?
Which one of these is the faster/better one?
这一项:
List<User> list = new List<User>();
User u;
foreach (string s in l)
{
u = new User();
u.Name = s;
list.Add(u);
}
或者这样的:
List<User> list = new List<User>();
foreach (string s in l)
{
User u = new User();
u.Name = s;
list.Add(u);
}
我的新手发展的能力告诉我,第一个是好,但我的一个朋友告诉我,我错了,但不能给我一个很好的理由,第二个是更好的。
My newbie-developing skills tells me the first one is better, but a friend of mine tells me im wrong, but could not give me a good reason why the second one is better.
有没有在所有的在性能上有什么区别?
Is there any difference in performance at all?
推荐答案
性能方面这两个例子被编译到相同的IL,所以没有区别。
Performance-wise both examples are compiled to the same IL, so there's no difference.
二是更好,因为它更清楚前presses你的意图,如果 U
循环中仅使用。
The second is better, because it more clearly expresses your intent if u
is only used inside the loop.
这篇关于声明内部或外部的foreach循环的变量:这是更快/更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文