c++functionassemblyparameters

Is it more efficient (or better in other ways) to modify an input parameter or declare a new variable and modify that?


I've got a code that as you can see I can write in either of two following ways, the matter is the only difference is since in second function the parameter is declared as non-constant I can use that instead of declaring a new variable(num1 in first function).

I'm curious which one would be more suited if there would be any difference between output assembly codes generated by compiler for each one:

void Test(const long double input){
 long double num=(6.0*input);
 long double num1=9.0;
 for (int i=0;i<5;i++)
  num1*=num;
 cout <<num1<<'\n';
}

void Test(long double input){
 long double num=(6.0*input);
 input=9.0;
 for (int i=0;i<5;i++)
  input*=num;
 cout <<input<<'\n';
}

Solution

  • Like this:

    void Test(long double input)
    {
        long double const factor = 6.0 * input;
        long double       result = 9.0 * pow(factor, 5);
    
        cout << result << '\n';
    }
    

    If you must use the loop then I would follow GMan's example.

    One variable for one use. Trying to re-use variables has no meaning. The compiler does not even have the concept of variable names. It re-uses slots when appropriate (notice I use the term slot: it multiple variables can use the same slot).

    The compiler is just so much better at optimization than a human that it is counter productive to try and beat it (use better algorithms this is were the human factor comes in because the compiler does not understand algorithms).

    The biggest thing about code is not writing it but maintaining it. So your code MUST be written to be easy to maintain for the next person (a company will spend much more on maintenance then developing new code). The old adage is write your code knowing that the maintainer is an axe murder that knows where you live.