Suppose I have some code like this:
public string SomeMethod(int Parameter)
{
string TheString = "";
TheString = SomeOtherMethod(Parameter);
return TheString;
}
Of course, this code is equivalent to this:
public string SomeMethod(int Parameter)
{
return SomeOtherMethod(Parameter);
}
I think the first version is more readable and that’s how I’m writing my code, even thought I’m using a variable when I know I could avoid it.
My question is this: does the compiler compile the code in the same way (ie same performance) or is the second option really better in terms of performance.
Thanks.
I’d say the first form is less readable and it contains a redundant initializer. Why initialize the variable to “” if you’re about to give it a different value? At least change it to:
or if you really want to separate declaration from initialization:
(Note that I’ve also adjusted the named to follow .NET naming conventions and to give a more meaningful name to the local variable -“TheString” conveys no useful meaning.)
You really won’t see any performance problems from using the local variable, but I’d really encourage you to think about the readability. What is the purpose of the local variable here? You’d presumably describe the method as: “Returns the result of calling
SomeOtherMethodwith the given parameter” – at which point, the one-line version implements exactly that description.