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

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

    In any case, the best way would be to use a constructor that takes a Name... or, otherwise, exploit curly-brace notation:

    foreach (string s in l)
    {
        list.Add(new User(s));
    }
    

    or

    foreach (string s in l)
    {
        list.Add(new User() { Name = s });
    }
    

    or even better, LINQ:

    var list = l.Select( s => new User { Name = s});
    

    Now, while your first example could, in some cases, be unperceptibly faster, the second one is better because it's more readable, and the compiler may discard the variable (and omit it altogether) since it's not used outsid the foreach's scope.

提交回复
热议问题