Home > Mobile >  Can out and ref be used as temporary variables?
Can out and ref be used as temporary variables?

Time:03-05

When we use out or ref inside calculations, with multiple assignments and reading from it, what drawbacks does it have? Will it hurt performance?

static bool SomeFunction(int x, int y, out int result)
{
    result = 8;
    for (int i = 0; i < x; i  )
    {
        result  = result   x;
        if (result == y)
            return false;
    }
    return true;
}

Or should we better be using additional variable:

static bool SomeFunction(int x, int y, out int result)
    {
        int temp = 8;
        for (int i = 0; i < x; i  )
        {
            temp  = temp   x;
            if (temp == y)
            {
                result = 0;
                return false;
            }      
        }
        result = temp;
        return true;
    }

CodePudding user response:

It turns out that the more calculations we do the more the difference between the performance of both.

I believe this is expected, since here we see an extra level of indirection. enter image description here

However, that's an extremely contrived case. In something even slightly more complicated like your original code, the difference becomes far less pronounced.

enter image description here

At any rate, you're talking about a difference of milliseconds over millions of iterations, so worrying about which of these approaches to take for performance reasons is almost certainly a premature optimization.

what drawbacks does it have?

Ignoring performance, you should definitely think about how the behavior of your code is impacted by this decision.

Let's say your function threw an exception, for example: would you want the value of result to have been changed in the output, even though no value was returned?

Or what if the value of the variable passed as your out parameter is being read by other threads? Do you want that variable's value to change as the function executes? Maybe you're using that variable to track the progress of your function's execution, in which case there's value to changing the value as you go. But if not, it's probably "tidier" to avoid changing the out variable until you've got a corresponding return value to go with it.

On that note, why use an out parameter at all? You could use a ValueTuple, enter image description here

LINQPad Benchmark

static (bool Found, int Result) SomeFunctionValueTuple(int x, int y)
{
    int temp = 8;
    for (int i = 0; i < x; i  )
    {
        temp  = temp   x;
        if (temp == y)
        {
            return (false, 0);
        }
    }
    return (true, temp);
}
static int? SomeFunctionNullable(int x, int y)
{
    int temp = 8;
    for (int i = 0; i < x; i  )
    {
        temp  = temp   x;
        if (temp == y)
        {
            return null;
        }
    }
    return temp;
}
  • Related