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.