tags:

views:

100

answers:

1

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

+8  A: 

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.

Andrew Hare
Thanks. So for the two code examples, they are pretty much the same under the hood. I fully understand your answer on my second query. :)
dotnetdev
If you declare variables at the top of the block, then assign to them later, you're unnecessarily calling their default constructor. Probably not a big deal in most cases.
George V. Reilly
George V. Reilly said "If you declare variables at the top of the block, then assign to them later, you're unnecessarily calling their default constructor" but this is only true in C++. The question was tagged as C# and no constructor get called in this case. The reference simply has the value null.
alexk7