在 foreach 循环内部或外部声明变量:哪个更快/更好? [英] Declaring a variable inside or outside an foreach loop: which is faster/better?
本文介绍了在 foreach 循环内部或外部声明变量:哪个更快/更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
其中哪个更快/更好?
这个:
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.
性能上有什么不同吗?
推荐答案
在性能方面,两个示例都编译为相同的 IL,因此没有区别.
Performance-wise both examples are compiled to the same IL, so there's no difference.
第二种更好,因为如果 u
仅在循环内使用,它会更清楚地表达您的意图.
The second is better, because it more clearly expresses your intent if u
is only used inside the loop.
这篇关于在 foreach 循环内部或外部声明变量:哪个更快/更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文