GurdeepS
GurdeepS

Reputation: 67213

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

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

Upvotes: 5

Views: 509

Answers (1)

Andrew Hare
Andrew Hare

Reputation: 351476

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.

Upvotes: 10

Related Questions