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

Viewed 3149

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.

3 Answers

The local variable is always optimised.

There is no performance impact of using a local variable before a return statement since the Compiler optimizes the code.

So, after the compilation, the Case 2 code will look exactly like Case 1.

  private string GetValue()
  {
     // string result = this.GetResult(); // this is optimized to the below line by compiler

     return this.GetResult();
  }

  private string GetResult()
  {
     // Code here that return a big string...
  }

See here for the actual output generated by the Compiler when we use a variable and when we don't before returning a result.

I prefer using the local variable always as it speeds up debugging. According to this, developers spend 75% of their time debugging.

Related