Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding return statements for C# methods improve performance?

Tags:

c#

.net

This blog says

12) Include Return Statements with in the Function/Method. How it improves performance Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application.

I'm fairly sure that this is a false statement. But wanted to get the opinion experts out there. What do you guys think?

like image 999
HashName Avatar asked Mar 05 '10 15:03

HashName


1 Answers

This statement does not apply to C#.

With C# you must explicitly set a "return" to have a valid function, without a return, you get a compile error to the effect of "not all code paths return a value".

With VB.NET this would apply as VB.NET does NOT have the requirement for an explicit return, and allows you to have functions that never return a value, as well as allow you to set the return using the name of the function.

To provide an example

In VB.NET you can do this

Function myFunction() As String
    myFunction = "MyValue"
End Function

Function myFunction2() As String
    'Your code here
End Function

The above compiles, neither with an explicit "returns", there is more overhead involved in this.

If you try to do this with C#

string myFunction()
{
    //Error due to "Cannot assign to 'myFunction' because it is a 'Method Group'
    myFunction = "test";
}

string myFunction2()
{
    //Error due to "not all code paths return a value
}

My comments note the errors that you get.

like image 161
Mitchel Sellers Avatar answered Sep 17 '22 13:09

Mitchel Sellers