Home > OS >  Is there a performance difference between assigning before returning and directly returning in C ?
Is there a performance difference between assigning before returning and directly returning in C ?

Time:04-19

Is there a performance difference between the two following functions, or is it handled by the compiler the same?

double f1(double a, double b) {
  return a   b;
}

double f2(double a, double b) {
  double sum = a   b;
  return sum;
}

Thanks.

CodePudding user response:

Is there a performance difference between the two following functions

One function contains two statements and the other contains one statement.

or is it handled by the compiler the same?

They can be. Both functions have identical observable behaviour, so they may produce an identical program.

CodePudding user response:

From the practical side, it helps to see what compilers actually do with such a piece of code, see this godbolt.

Turns out that starting from `-O1´ optimization level, g and clang for example create the exact same assembler instructions:

    addsd   xmm0, xmm1
    ret

Meaning the performance would of course also be exactly the same.

  • Related