+ 1

string view is beneficial over const string& or not

Hi Please refer code below: string_view is also not allocating new memory and const string& also help us avoid string copy. Is there any other benifit of using string view? As showcased in code, I am aware that substring of string view is better than substring of string. But in case I need only whole string for viewing purpose, has string view a better performance compared to constant string ref? https://sololearn.com/compiler-playground/cRRal1Yk3jHT/?ref=app

17th Dec 2023, 6:35 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Antworten
+ 2
In the provided code, you've illustrated the memory allocation behavior of different string-related operations. You correctly pointed out that both `const string&` and `string_view` can avoid unnecessary memory allocation for string copies. The key benefit of `string_view` lies in its ability to efficiently represent a view into a portion of a string without creating a new string or allocating additional memory. This is particularly useful when you are working with substrings or portions of a larger string. In your example, the function `printSubString2` using `const string&` creates a new string using `substr`, which may involve memory allocation. On the other hand, `printSubString3` using `string_view` does not allocate additional memory, making it more efficient when you only need a view into a substring. So, the main advantage of `string_view` is its lightweight nature for representing substrings or views into existing strings without the overhead of memory allocation and copying. This can be especiall
17th Dec 2023, 6:40 AM
卂ㄚㄩ丂卄
卂ㄚㄩ丂卄 - avatar
+ 2
here is another SO answer to a question similar to yours: https://stackoverflow.com/questions/40127965/how-exactly-is-stdstring-view-faster-than-const-stdstring basically, stringview is straight referencing instead of first parsing to string as in the case of const string&
17th Dec 2023, 9:50 AM
Bob_Li
Bob_Li - avatar
+ 1
[Listen Once🌙] Ketan Lalcheta was asking about the advantage of using string_view over using const string& when storing a string to memory.
31st Dec 2023, 4:55 AM
Bob_Li
Bob_Li - avatar