[ad_1]
I had an interview, where I get the following function declaration:
int f1(const std::vector<int> vec)
I suggested that instead of copying the vector, we should use a const-reference(not to mention that const copy does not makes much sense), but the interviewer claimed that the compiler copy-elision will handle it. I couldn’t come up with any strong argument at the spot, but today I did some research.
I implemented the following two simple example functions:
int f1(const std::vector<int> vec) {
const auto num = vec.size();
return num * num;
}
int f2(const std::vector<int>& vec) {
const auto num = vec.size();
return num * num;
}
From the godbolt assembly, it is clear that the f2
function has 2 additional instructions so it should be slower. (I think 2 mov
is technically almost free in modern CPUs)
I also used quick-bench to measure the two solutions, but it is confirmed my suspicion, that passing const-ref is faster. (even for 1 element)
I suspected that maybe copy-elision is not allowed because of benchmark::DoNotOptimize(result);
, but after removing it, I received a similar result.
Now I have these results, but I think it is still not convincing enough.
What do you think?
Do you have any good argument for using one over the other?
[ad_2]