Pass by value if the type is smaller than or comparable to a pointer; for example, int, char, double, small structs, ...
Pass by reference for larger objects; for example, STL containers. I've read a lot about compilers being able to optimize it but they didn't at my simple benchmark that follows. Unless you want to waste time testing use cases, use const T& obj
.
Bonus: For faster speed use restrict
from c99 (this way you catch up to fortran, which restricts pointer aliasing; use case: f(const T&__restrict__ obj)
. C++ standard doesn't allow restrict
keyword but compilers use internal keywords -- g++ uses __restrict__
. If there is no aliasing in the code, there is no speed gain.
the benchmark with g++ 4.9.2:
Passing vector by reference:
> cat inpoint.cpp
#include <vector>
#include <iostream>
using namespace std;
inline int show_size(const vector<int> &v) {
return v.size();
}
int main(){
vector<int> v(100000000);
cout << show_size(v) << endl;
return 0;
}
> g++ -std=c++14 -O2 inpoint.cpp; time ./a.out
100000000
real 0m0.330s
user 0m0.072s
sys 0m0.256s
Passing vector by value takes twice as much time:
> cat invalue.cpp
#include <vector>
#include <iostream>
using namespace std;
inline int show_size(vector<int> v) {
return v.size();
}
int main(){
vector<int> v(100000000);
cout << show_size(v) << endl;
return 0;
}
> g++ -std=c++14 -O2 invalue.cpp; time ./a.out
100000000
real 0m0.985s
user 0m0.204s
sys 0m0.776s