Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance impact to block level vs function level scoping in .NET

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?

like image 237
Matthew Nichols Avatar asked Oct 18 '15 15:10

Matthew Nichols


People also ask

What determines the visibility of variables and methods in C#?

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.

Can scopes be nested in C#?

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.

How does scope work in C#?

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.

Is scope and visibility same?

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.


1 Answers

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.)

like image 89
Guffa Avatar answered Oct 09 '22 11:10

Guffa