I want to test speed of the passing by value and passing by reference in C++:
class MyAddress{
char *name;
long int number;
char *street;
char *town;
char state[2];
long zip;
std::vector<int> v_int;
public:
MyAddress(int i){
v_int.resize(1000000);
std::fill(v_int.begin(),v_int.end(),i);
}
MyAddress& assign1(MyAddress const& x)
{
MyAddress tmp(x); // copy construction of tmp does the hard work
std::swap(*this, tmp); // trade our resources for tmp's
return *this; // our (old) resources get destroyed with tmp
}
MyAddress& assign2(MyAddress x)//x is a copy of the source
{ //hard work already done
std::swap(*this, x); // trade our resources for x's
return *this; // our (old) resources get destroyed with x
}
void f1(MyAddress v){int i=v.v_int[3];}
void f2(MyAddress const &ref){int i=ref.v_int[3];}
};
MyAddress get_names(MyAddress& ref){return ref;}
main:
int _tmain(int argc, _TCHAR* argv[])
{
float time_elapsed1=0;
float time_elapsed2=0;
for(int i=0;i<100;i++){
{
MyAddress a1(1);
MyAddress a2(2);
MyAddress a3(3);
clock_t tstart=std::clock();
a1.f1(a2);
a1.f1(a3);
clock_t tend=std::clock();
time_elapsed1+=((float)tend-(float)tstart);
}
{
MyAddress a1(1);
MyAddress a2(2);
MyAddress a3(3);
clock_t tstart=std::clock();
a1.f2(a2);
a1.f2(a3);
clock_t tend=std::clock();
time_elapsed2+=((float)tend-(float)tstart);
}
}
std::cout<<std::fixed<<"\nassign1 time elapsed : "
<<time_elapsed1/CLOCKS_PER_SEC;
std::cout<<std::fixed<<"\nassign2 time elapsed : "
<<time_elapsed2/CLOCKS_PER_SEC;
system("pause");
return 0;
}
The time difference result is shocking:
assign1 time elapsed : 81.044998
assign2 time elapsed : 0.002000
is this correct?
How can the speeds for “by value” be so much more than “by reference”?
There is some confusion in the wordings of your ouput: you’re not using
assign1andassign2anywhere in your code, yet you’ve mentioned them in the output.Anyway, after seeing what you’re actually doing, all I can say that
f1takes the argument by value which means it calls the copy-constructor, which in turn copies the member vector which is too huge. This copying of the vector takes that much time, which you save when you callf2as it takes the argument by reference, so no copy of the vector is made in this case.