Re: Call by value vs. Call by reference
cout << "f1 called" << '\n';
for (int i = 0; i < 10; i++) {
vector<int> v;
f1(v);
}
cout << "f1 end" << '\n';
v.clear();
cout << "f2 called" << '\n';
for (int i = 0; i < 10; i++) {
vector<int> v;
f2(v);
}
cout << "f2 end" << '\n';
v.clear();
cout << "f3 called" << '\n';
for (int i = 0; i < 10; i++) {
vector<int> v;
f3(&v);
}
The problem with your benchmark is that most of the work is done
within the functions themselves.
I have learned when an object is big, I should pass the object using a
reference or pointer to it rather than calling by value.
That's true, but you must understand why. The reason is that when
calling by value, you make a copy of the object, and copying that
object takes time.
But in your example, you just pass an empty vector, and that's quite
quick to copy.
Furthermore, it's only _starting_ the function that suffers when
calling by value, not the work done _inside_ it.
So, to make your benchmark work better, strip the body of your
functions and call your functions more times.
The code below should show the difference quite clearly (part 1 took
about 3 minutes, and part 2 was under a second on my system).
//speedtest.cpp
#include <vector>
#include <iostream>
using namespace std;
double f1(vector<double> in) {
return in[0];
}
double f2(vector<double> &in) {
return in[1];
}
int main() {
vector<double> vec(1000000); //big vector
vec[0]=1.2;
vec[1]=3.4;
double db;
int bigNum = 10000;
cout << "start f1:\n" << endl; //remember to flush...
for (int i=0;i< bigNum ;i++) {
db = f1(vec);
}
cout << "start f2:\n" << endl;
for (int i=0;i< bigNum ;i++) {
db = f2(vec);
}
cout << "end" << endl;
return 0;
}