Should we use temporary variables for the returned values of functions?

Posted by totymedli on Stack Overflow See other posts from Stack Overflow or by totymedli
Published on 2012-12-19T16:53:16Z Indexed on 2012/12/19 17:03 UTC
Read the original article Hit count: 194

Filed under:
|

I thought about this: Is there a performance difference in these two practices:

  1. Store the return value of a function in a temporary variable than give that variable as a parameter to another function.
  2. Put the function into the other function.

Specification

Assuming all classes and functions are written correctly.

Case 1.

ClassA a = function1();
ClassB b = function2(a);
function3(b);

Case 2.

function3(function2(function1()));

I know there aren't a big difference with only one run, but supposed that we could run this a lot of times in a loop, I created some tests.

Test

#include <iostream>
#include <ctime>
#include <math.h>
using namespace std;

int main()
{
   clock_t start = clock();
   clock_t ends = clock();

   // Case 1.
   start = clock();
   for (int i=0; i<10000000; i++)
   {
      double a = cos(1);
      double b = pow(a, 2);
      sqrt(b);
   }
   ends = clock();
   cout << (double) (ends - start) / CLOCKS_PER_SEC << endl;

   // Case 2.
   start = clock();
   for (int i=0; i<10000000; i++)
      sqrt(pow(cos(1),2));
   ends = clock();
   cout << (double) (ends - start) / CLOCKS_PER_SEC << endl;
   return 0;
}

Results

  • Case 1 = 6.375
  • Case 2 = 0.031

Why is the first one is much slower, and if the second one is faster why dont we always write code that way? Anyway does the second pratice has a name?
I also wondered what happens if I create the variables outside the for loop in the first case, but the result was the same. Why?

© Stack Overflow or respective owner

Related posts about c++

Related posts about Performance