Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables as late as possible and passing returning method as a parameter

Tags:

performance

c#

If I have code like this:

string s = MyClass.GetString(); // Returns string containing "hello world";
ProcessString(s);

Is this any slower than?

ProcessString(MyClass.GetString());

If so, why? In the second example, is the compiler generally making a variable from the GetString(); method which returns a string?

Also, what is the benefit of declaring variables as late as possible? Does this benefit the GC? If so, how (I'm assuming in terms of GC gens)?

Thanks

like image 723
GurdeepS Avatar asked Sep 10 '09 19:09

GurdeepS


People also ask

Can you declare a variable in a parameter?

Parameter, local, and instance variablesParameters are declared in between the parentheses in the header of a method. Local variables are declared between the curly-braces of a method, in a statement (which needs to end with a semicolon).

What is the correct way for declaring the variable?

Always use the '=' sign to initialize a value to the Variable. Do not use a comma with numbers. Once a data type is defined for the variable, then only that type of data can be stored in it. For example, if a variable is declared as Int, then it can only store integer values.

Do you have to declare a variable every time you use it?

All variables must be declared before they can be used.


1 Answers

No, the compiler will emit identical IL for both of those examples (not all examples like this, mind you, just this example specifically).

Remember that any local variables in C# all get bagged up together in the IL at the top of the method so it doesn't really matter when you declare them as the CLR will allocate space for them upon entering the method.

The benefit of declaring variables as late as possible is solely to improve the readability of your code. Declaring variables as close as possible to where they are used allows readers of you code to glean contextual information about what the variable is and does beyond the name of the variable alone.

like image 116
Andrew Hare Avatar answered Sep 30 '22 14:09

Andrew Hare