Should I instantiate my worker variables inside or outside my for loop
E.g.
a)
bool b = default(bool); for (int i = 0; i < MyCollection.Length; i++) { b = false; foreach(object myObject in myObjectCollection) { if (object.Property == MyCollection[i].Property) { b = true; break; } } if (b) { DoSomethingWith(MyCollection[i]); } }
b)
for (int i = 0; i < MyCollection.Length; i++) { bool b = default(bool); foreach(object myObject in myObjectCollection) { if (object.Property == MyCollection[i].Property) { b = true; break; } } if (b) { DoSomethingWith(MyCollection[i]); } }
EDIT: Seems universally agreed that there will be no difference where the IL is concerned. But for readability and clarity of scope… inside is better
Previous answer deleted as I’d misread the code. (Using ‘default(bool)’ anywhere is a bit odd, btw.)
However, unless the variable is captured by a delegate etc, I’d expect them to either compile to IL which is effectively the same (in terms of both behaviour and performance).
As ever, write the most readable code first. Micro-optimising things like this is asking for trouble. I agree with the others who have suggested that you restrict the scope of variables as much as you can – so if you need it after the loop, you haven’t got any choice anyway; otherwise declare it inside.
Okay, here’s a test program:
Generated IL (just
csc Test.cs):The only differences are where the variables are located within the stack.