Lukas-T
Lukas-T

Reputation: 11340

Is there any case when passing by const & is not optimal for strings?

Recently I mentioned to a relative new user, that he should pass string parameters as const std::string & instead of passing them by value and received a comment:

passing by const ref is not necessarily better then passing by a const value. Especially if you frequently read from it in the function.

While searching I only found the rule of thumb that recommends to use & or const & for any type X where sizeof(X) > sizeof(void *).

So what could be such a case, where passing a string by (const) value is better than passing it by const &, if there is any?

Upvotes: 0

Views: 81

Answers (1)

eerorika
eerorika

Reputation: 238311

Is there any case when passing by const & is not optimal for strings?

In cases where the caller doesn't have a std::string object in the first place, creating one in order to pass a reference is non optimal. std::string_view argument covers these cases, as well as most cases where string reference is optimal.

what could be such a case, where passing a string by (const) value is better than passing it by const &, if there is any?

The text that you quote describes such case:

... Especially if you frequently read from it in the function.

To explain why: Copying into an argument occurs only once per function call, while indirection through a reference (or string view) occurs on every access within the function. Given that neither is free, there must be some number of indirections that are more expensive than the copy.

Whether that number is ever reached in your program is another matter. The number is heavily influenced by the capabilities of the system, and length of the input string. If you measure that passing by value is statistically faster (with a reasonable p-value) in your program on your target system, then it may be worth it. But this is quite rare case, which is why the reference (or string view) is recommended default choice unless the function needs a copy.

Note that passing by const value is often not a good idea since it forces the function to copy the string again in cases where it could otherwise move it.

Upvotes: 4

Related Questions