I thought about this: Is there a performance difference in these two practices:
- Store the return value of a function in a temporary variable than
give that variable as a parameter to another function.
- 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…