Best practice for creating objects used in for/foreach loops
What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:foreach(var a in collection)
{
SomeClass sc = new SomeClass();
sc.id = a;
sc.Insert();
}
or
SomeClass sc = null;
foreach(var a in collection)
{
sc = new SomeClass();
sc.id = a;
sc.Insert();
}
开发者_运维问答Which is better?
The first way is better as it more clearly conveys the intended scope of the variable and prevents errors from accidentally using an object outside of the intended scope.
One reason for wanting to use the second form is if you want to break out of the loop and still have a reference to the object you last reached in the loop.
A bad reason for choosing the second form is performance. It might seem at first glance that the second method uses fewer resources or that you are only creating one object and reusing it. This isn't the case here. The repeated declaration of a variable inside a loop doesn't consume any extra resources or clock cycles so you don't gain any performance benefit from pulling the declaration outside the loop.
First off, I note that you mean "creating variables" when you say "creating objects". The object references go in the variables, but they are not the variables themselves.
Note that the scenario you describe introduces a semantic difference when the loop contains an anonymous function and the variable is a closed-over outer varible of the anonymous function. See
http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/
for details.
I'm sure someone might whip out the MSIL analysis, but practically there is no discernible difference in execution or performance. The only thing you're affecting is the storage of an object reference.
I say keep it clean and simple; declare the variable inside the loop. This provides the open/closed principle in practice, so you know the scope the variable is used and is not reused elsewhere. On the next loop, the variable loses scope and is reinitialized automatically.
You are creating a new object in each loop iteration in both cases (since you call new SomeClass()
).
The former approach makes it clear that sc
is only used inside the loop, which might be an advantage from a maintenance point of view.
I think it does not matter for performance, but I prefer the first one. I always try to keep declaration and instantiation together if possible.
I would go with option 2 to be tidy, to keep all declarations in one place. You may say that "objects should only be declared where and when they are needed" but your loop would probably be in its own little method.
I would use the first one, but for compiler it is the same, because compiler moves out declaration of variables from the loops. I bet after compiling the code would look like second one.
精彩评论