std::string_view it’s class which can view std::string or const char* without ownership and without additional memory requesting.
SSO (Small string optimization)
std::string has optimization for small strings ( compiler specific feature, for gcc, clang and msvc there are different values ).
For example for GCC 7.3 this value is 16 bytes. If string has <=16 bytes it will be saved in stack inside std::string object. If more then 16 bytes, then data used for saving string will be in heap. Which means additional memory allocations.
1 2 |
std::string str(“123”); // no additional memory allocations std::string str(“1111111111111111111111111111111111111111”); // additional memory allocations |
It can be checked by overloading operator new in global space.
1 2 3 4 |
void* operator new(std::size_t count) { std::cout << count << “ bytes” << std::endl; return malloc(count); } |
For example we have function:
1 2 3 4 5 6 7 8 |
void PrintString(const std::string& str) { std::cout << str << std::endl; } int main() { const chat* str = “123123123123123123123”; PrintString(str); // additional memory allocations for string } |
In this example we will have constructed std::string object with additinal memory allocations. new() operation is high costed because it will call kernel method to get new space.
std::string_view allows to avoid additinal allocations.
1 2 3 4 5 6 7 8 |
void PrintString(std::string_view& str) { std::cout << str << std::endl; } int main() { const char* str = “123123123123123123132”; PrintString(str); // without any additional memory allocations } |
It will be worse case if inside method will be called substr() method.
1 2 3 4 5 6 7 8 |
void PrintString(const std::string& str) { std::cout << str.substr(5) << std::endl; } int main() { ... PrintString(str); // two memory allocations } |
We will have two memory allocations , first time create std::string object, second time substr() allocate memory for substring.
std::string_view has almost all methods the same as std::string except modifing methods.
So with std::string_view substr() method we will also avoid additinal memory allocations.
1 2 3 |
void PrintString(std::string_view str) { std::cout << str.substr(5) << std::endl; // no any memory allocations } |
Related standard document: p0254r2