0

Suppose I have the following two examples, will there be any difference between putting the variable declaration outside of the loop VS inside the loop, especially performance wise? Note: A new object is always being created inside the loop.

Method 1: 
foreach (string name in nameList)
{
    Person person1 = new Person();
    person1.fullname = name;
}

Method 2:
Person person1 = null;
foreach (string name in nameList)
{
    person1 = new Person();
    person1.fullname = name;
}
  • you said it. a new object is created inside the loop. (and discarded) which would possibly give garbage collection overhead. – Randy Jul 25 '13 at 15:15

1 Answers1

0

It's a micro-optimization. So no, performance wise, it doesn't really matter. Any difference in performance will be made irrelevant in practically all non-trivial programs. And it's entirely possible that an optimizer would convert the less efficient form to the more efficient form (don't ask me which is which).

I'd prefer the first since it's slightly less code and limiting variable scope as much as possible is generally considered good practice.

Actually, to be more similar to method 1, method 2 should look like this:

Person person1 = null;
foreach (string name in nameList)
{
    person1 = new Person();
    person1.fullname = name;
}
person1 = null;

Because after the loop, person1 will still point to the object created in the last iteration, the garbage collector will only be able to free that object once person1 leaves scope or is assigned a different value (i.e. null). If this is in a terminating code block that doesn't do much else, it will leave scope at the end of the block, thus the null assignment is not really necessary.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138