I was reviewing some C# code and came across some variables that were scoped at the function level that I would have scoped inside the code block (a loop in this case) where they are used. To me scoping as close to the is just cleaner and easier to reason about and that is reason enough to prefer block level scope. But I was wondering, is there any significant performance impact one way or another?
Asked
Active
Viewed 203 times
6
-
Twould depend on the size of the loop and variable -- in most cases probably no differance – Alex Krupka Oct 18 '15 at 15:20
-
related http://programmers.stackexchange.com/questions/113262/why-declare-variables-close-to-where-they-are-used – Rotem Oct 18 '15 at 15:23
-
@AlexKrups Would it? I imagine the compiler would hoist the declaration out of the loop either way. – Rotem Oct 18 '15 at 15:24
-
It makes no difference whatsoever. .NET compilers generate MSIL, it doesn't have the notion of block scope. Some details on how the jitter tracks local variable use in [this post](http://stackoverflow.com/a/17131389/17034). Focus only on writing readable code. – Hans Passant Oct 18 '15 at 15:25
-
Cannot comment with out see code. Please supply code in question. – Seabizkit Oct 18 '15 at 15:27
-
@Rotem I guess i didn't fully think this through - I assume that the GC is smart enough to dispose of the last iteration of the item at the conclusion of the loop as opposed to the conclusion of the function? – Alex Krupka Oct 18 '15 at 15:34
1 Answers
9
There is no performance difference at all.
The variable scope is different from the variable lifetime. The variable is created in stack frame for the function, regardless if it is declared in the function scope or in a code block in the function. The variable exists during the entire function execution, it's only the compiler that limits the access to the variable depending on its scope.
(Note though that different rules apply if the variable is actually a part of a closure instead of a regular local variable.)

Guffa
- 687,336
- 108
- 737
- 1,005
-
And of course the JITter is free to reuse a register or part of the stack for multiple variables with non overlapping live times. – CodesInChaos Oct 18 '15 at 15:29
-
That is along the lines that I figured, though I had thought that perhaps the difference in scoping might effect garbage collection. – Matthew Nichols Oct 18 '15 at 15:59
-
@MatthewNichols: Actually it doesn't affect garbage collection either (except in debug mode). The garbage collector only cares about where in the code the reference is used, the scope and the lifetime of the variable is irrelevant. – Guffa Oct 18 '15 at 16:56
-
@Guffa yes that is what I figured out from your answer. I should brush up on my garbage collection lore. – Matthew Nichols Oct 18 '15 at 17:40