The question is a bit unclear, since the two are semantical very different.
Passing a non-const reference means return by parameter - ie. you modify the value inside the function at some point and the original input value may be used or not. Since you can only point the string_view to something else and are not allowed to modify the contents. So I should expect the following - the function uses the input string_view for something and then later points this input strint_view to something else. A semantical improvement would be:
void fun(std::string_view& a);
improved version:
std::string_view fun(const std::string_view& a);
even better solution (semanticly):
std::string_view fun(std::string_view a);
Now It is easier to provide the input and I get to choose myself if I want my input string_view
repoint'ed.
Other than that the reference is at a disadvantage here due to the following:
- Semantical a copy is better: it is easier to reason about a copy than
a reference (even a
const
one).
- If performance is a consideration as well, the reference stands at a
disadvantage in most scenarios and at best it looks like it will only be roughly on par with the copy. Demonstation using clang: https://godbolt.org/z/UR68km (results can vary due to compiler)
Please note even if the copy turned out to be slower by a small margin - it should still be the preferred method of passing.
I usually find myself using the following mnemonic when writing functions:
Pass by const reference, return by value. Except when you can, pass
by value instead.
It's fairly fitting here. The when you can includes when theres no potential large data copy involved and this is case here (there may be situations when reference is the only option). Using this rule of thumb ensures you don't make extra large data copies by accident. Apart from scalars, the most notable class types that should be passed by value is those that fall within the proxy category (for example smart pointers and views).
Only rarely should you pass by non-const reference - the usual case is when a buffer is modified. The same goes for pointers to some extent.