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

前端 未结 10 1777
灰色年华
灰色年华 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条回答
  •  执念已碎
    2020-11-27 15:28

    In this scenario, the second version is better.

    In general, if you only need to access the value within the body of the iteration, then choose the second version. On the other hand, if there is some final state the variable will hold beyond the body of the loop, then declare then use the first version.

提交回复
热议问题