15

This blog says

  1. 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?

4
  • 4
    Seems fishy, indeed, but I'll let the JIT gurus weight in ! Commented Mar 5, 2010 at 15:38
  • 4
    There are more fishy statements. "Use 'ArrayLists' in place of arrays", "Design with ValueTypes". I mean, ArrayLists? That's great with the boxing. And knowing exactly when to use structs instead of classes is something many, if not most people mix up - including me. Strange "tip". Commented Mar 5, 2010 at 15:47
  • Along the lines of @Razzie's remark, I'd take that post with a grain of salt, it doesn't take into consideration items added even in the .NET 2.0 days.... Commented Mar 5, 2010 at 15:53
  • 6
    Specific micro-optimization performance advice that is not accompanied by empirical data demonstrating a measurable effect is of relatively low value. Commented Mar 5, 2010 at 16:30

6 Answers 6

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I read the OP's quoted text from the blog as meaning using return statements to short-circuit processing as in Nick's guess.
4

The post is kind of vague. Being a C# developer, my first thought was "as opposed to what?". However, he could be referring to something like:

public bool MyFunction()
{
    bool result = false;
    if (someCondition == true)
    {
        // Do some processing
        result = true;
    }
    else if (someOtherCondition == true)
    {
       // Do some processing
       result = true;
    }
    // ... keep going

    return result;
}

He may be suggesting that replacing the result = true; statements with return true; may perform better. I'm not sure about that personally... that's pretty deep into JIT theory at that point, and I think any gains that are made would be very minor compared to other performance improvements that you could make.

1 Comment

Agree with this - it's one of those times where you have to decide that maintainability is more important than the insignificant performance gain!
3

I'd disagree - I think a single in and single out of every method makes code much easier to read and debug. Multiple return statements in a function can make navigating code more comlpex. In fact (if possible to refactor) its better to have more smaller functions than say larger functions with multiple exits.

Comments

2

It is somewhat true, both for VB.NET and C#. In C# the programmer has to declare the variable that holds the return value explicitly, it is automatic in VB.NET. Most return values are returned in the EAX or RAX register, the JIT compiler has to generate code to load the register from the return value variable before the function exits. When you use the return statement, the JIT compiler might have the opportunity to load the EAX register directly, or already have the register containing the correct value, and jump to the function exit code, bypassing the load-from-variable instruction.

That's a pretty big "might" btw, real code invariably tests some expression with the if() statement. Evaluating that expression almost always involves using the EAX register, it still has to be reloaded with the return value. The x64 JIT compiler does a completely different job doing that compared to the x86 compiler, the latter always seems to use the variable in a few spot checks I did. So you're not likely to be ahead unless you run on a 64-bit version of Windows.

Of all the evil in premature optimization, this one is arguably the worst. The potential time savings are minuscule, write your code for clarity first. Profile later.

1 Comment

There is one case that the return syntax simplify for the compiler it's tail call recursion optimization as it is slightly easier to do when the return call are here as there is no need to trace the rest of the code to find if the call is tail-recursive or not (just look for jumps to the end of the method body). But I don't know the current state of the JIT compiler regarding this specific case so it may even not be a problem.
1

My only guess here is that he's talking about VB.NET not C#. VB.NET allows you to somethin like this to return values

Public Function GetSomething() As Int
     GetSomething = 4
End Function

My VB is incredibly out of date though. This may be slower that using an explicit return statement

6 Comments

Additionally this post : stackoverflow.com/questions/451025/vb-net-function-return speak about performance and the Return statement in VB.Net : The il generated seem nearly the same ergo the speed is the same. (I didn't do a disassembly myself but the one presented in this question seem logical)
@dotjoe: How so? This is actually quite useful for cases where you would, in C#, have to declare a result (or similar) variable. Personally, I have fully adapted the C# style but I can’t form a convincing argument why the VB style should be worse. For me, it’s simply a matter of habit, and the VB way of doing this is perfectly reasonable.
@Konrad Rudolph wait...this syntax is not the same as Return 4? Does it holds the result until the end of the function and can be set multiple times?
@dotjoe : Yes as in Pascal and some other languages, C# hide the variable allocated on the stack for the return value from you but it is still there. I prefer the C# way of doing things but it's only a personal taste. Additionally the "Return" syntax could help to ensure that you have strictly functional code when needed as there is no way to mutate the return value without explicitly declaring a temporary variable.
I guess that could be useful...I've never seen it used that way so I'll retract my statement. Still seems like it would confuse the shit out of most c/java people. Especially if it was done in a recursive function.
|
0

Generally there are 2 spots in which I exit a function. At the very beginning of my methods to validate incoming data:

if (myParameter == null)
   throw new ArgumentNullException("myParameter");

And/or at the very end of the method.


private bool GetSomeValue()
{
    bool returnValue = false;
    // some code here
    if (some condition)
    {
        returnValue = some expression
    }
    else
    {
        returnValue = some other expression;
    }
    return returnValue;
}

The reason I don't return inside of the conditional, is so that there is 1 exit point of the function, it helps with debugging. No one wants to have to maintain a method with 12 return statements in it. But that is just a personal opinion of mine. I would err on the side of readability, and not worry about optimization unless you're dealing with a real-time must-go-faster situation.

4 Comments

IMO the single return point notion is irrelevant in modern software. I'd rather immediately see a return statement and know the code exited than having to wonder if returnValue gets manipulated somewhere else further down the method if you could have returned from inside those if blocks.
@ChrisMarisic - I agree. The multiple-returns-is-bad argument adds noise to the code. If you have to return in 5 places, that can't be worse than branching 5 ways to the end with the possible changing state with the possible reader not following the intent.
@Kit I had to read your comment a couple of times to make sure I understood it. I agree with you, choosing to delay returning when you can return immediately will add noise to the code.
@ChrisMarisic - Hm, guess I should have returned from the comment early! It was a bit of a run-on, eh?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.