Declaring a variable inside or outside an foreach loop: which is faster/better?

前端 未结 10 1796
灰色年华
灰色年华 2020-11-27 14:58

Which one of these is the faster/better one?

This one:

List list = new List();
User u;

foreach (string s in l)
{
    u = new         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 15:32

    Performance-wise both examples are compiled to the same IL, so there's no difference.

    The second is better, because it more clearly expresses your intent if u is only used inside the loop.

提交回复
热议问题