Is there any performance hit or memory consumption difference to creating a temporary variable in a function compared to returning directly the value assigned to this variable?
For example, which of these functions (GetValue) are better in performance and for saving memory or both are exactly the same:
Case 1:
private string GetValue()
{
return this.GetResult();
}
private string GetResult()
{
// Code here that return a big string...
}
Case 2:
private string GetValue()
{
string result = this.GetResult();
return result;
}
private string GetResult()
{
// Code here that return a big string...
}
Thank you.
In these basic situations, readability always trumps performance differences. I'd consider this a micro-optimisation at best, and these largely turn out to be wastes of time. What you save on this will be eaten up by an undeterministic GC run.
Most of the time there are no differences in the resulting code if the compiler is allowed to optimise it. The resulting IL in this case seems to have a few extra op codes for a reference to the string on the stack, but what the JIT then does with this is anyone's guess.
I sometimes break out into temporary variables to review them before returning, but I never worry about the performance impact. Most importantly, I have never seen a case where this sort of improvement was required to solve a performance problem.
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