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
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).
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.
All variables must be declared before they can be used.
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.
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