Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between returning a value directly or creating a temporary variable

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.

like image 221
Samuel Avatar asked Aug 03 '12 14:08

Samuel


1 Answers

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.

like image 71
Adam Houldsworth Avatar answered Oct 17 '22 02:10

Adam Houldsworth