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

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

    The 2nd one is better. You are meaning to have a new user in each iteration.

    0 讨论(0)
  • 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<User> users = l.Select(name => new User{ Name = name }).ToList();
    
    0 讨论(0)
  • 2020-11-27 15:27

    Another reference which looks like above:

    http://social.msdn.microsoft.com/forums/en-US/csharplanguage/thread/d43aaba5-a58b-4610-bea4-5bc5d6741f98

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题