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?
Access Specifier − This determines the visibility of a variable or a method from another class. Return type − A method may return a value. The return type is the data type of the value the method returns.
In fact, a variable's scope is always the full extent of the code block it is declared within. As has been demonstrated throughout the tutorial, code blocks can be nested.
In C#, the Scope of the variable determines the accessibility of the variable to a particular part of the application. Variables can be declared within the class, method, and code block of a loop, condition, etc.
scope is... the largest region in which the name potentially is valid. The visibility of an identifier is the region of program text from which the object associated with the identifier can be legally accessed.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With