Search code examples
c#performance-testingvariable-declaration

Declaring variables for intermediate calculations and performance


Sorry this is such a dumb question, but I just have to ask this. I have a program that runs billions of calculations and I'm trying to get it to run faster. In my program, I declare a lot of variables for intermediate calculations. For example, in pseudo code:

public bool FunctionThatGetsCalledInMain(manyparameters)
{
    for (int i = 0; i < 10000000; i++)
    {
        int x = bigFunctionThatReturnsAnInt(i,manyparameters)
        double y = bigFunctionThatReturnsADouble(i,manyparameters)
        string z = bigFunctionThatReturnsAString(i,manyparameters)

        bool b = someFunctionOfXYZ(x,y,z)
    }
}

I'm wondering if I can improve performance by doing something like:

public bool FunctionThatGetsCalledInMain(manyparameters)
{
    for (int i = 0; i < 10000000; i++)
    {
        bool b = someFunctionOfXYZ(bigFunctionThatReturnsAnInt(i,manyparameters),bigFunctionThatReturnsADouble(i,manyparameters),bigFunctionThatReturnsAString(i,manyparameters))
    }
}

I know it looks horrendous, and my intuition tells me it doesn't really matter, but I just wanted to see if others agree.


Solution

  • Don't try to "optimize" the performance this way. Modern compilers will produce the identical code from both versions, so there will be no any difference in terms of performance, but your code will be unreadable.

    In general first case is much more readable, and that's why preferred. It clearly names temporary variable, that helps to understand code better. Moreover, it's much easier to debug.