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

前端 未结 10 1792
灰色年华
灰色年华 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:25

    A declaration does not cause any code to be executed, so it's not a performance issue.

    The second one is what you mean, and you're less likely to make a stupid error if you do it the second way, so use that. Always try to declare variables in the smallest scope necessary.

    And besides, the better way is to use Linq:

    List users = l.Select(name => new User{ Name = name }).ToList();
    

提交回复
热议问题