So I am reading code written for newer versions of CPP and frequently see string_view literals used almost exclusively, even in simple use cases.
For example:
std::cout<<"Hello world"sv<<std::endl;
Is there any particular reason for that? It is obviously not about storage duration, because string_view only wraps string literal. Do the string_view's have lower overhead or something?
Thanks you for your time.
CodePudding user response:
Shown example do not introduce any significant gains.
The only case where there might be a difference is when you use zero inside literal:
std::cout << "zerro \0insde"sv << std::endl;
std::cout << "zerro \0insde" << std::endl;
https://godbolt.org/z/54v1a518f
CodePudding user response:
Creating a std::string
can be costly as it often involves allocating memory dynamically. When the cost of creating a std::string
is a concern, using const char*
and length parameters as an alternative may reduce the expense, but it can also make the code less readable and harder to use.
std::string_view
, introduced in C 17, is a non-owning, read-only reference to a sequence of characters. Its purpose is to provide a way for functions to take a read-only reference to an object resembling std::string
, without needing to specify the exact type. The downside of using a const std::string&
in such cases is that it creates a std::string
object.
std::string_view
is a lightweight object that holds a pointer to the original string, and its length. Because it doesn't own the memory it points to, it doesn't need to manage the memory itself, which can make it more efficient than std::string
. However, it can also have more overhead in certain cases. For example, if a std::string_view
is frequently copied, it will need to create a new object each time, which can be more expensive than copying a std::string
.
Additionally, because it doesn't own the memory it points to, it must ensure that the original string remains valid as long as the std::string_view
is being used, which can also add some overhead.
P.S. be careful and use it with caution, as you do not own it
Additionally really great article to read https://quuxplusone.github.io/blog/2021/11/09/pass-string-view-by-value/