Benchmarking std::{string, string_view, reference_wrapper}

submited by
Style Pass
2024-10-14 08:00:06

A C++ mantra is that you don't pay for what you don't use1. It turns out that std::string has quite a long list of jobs, with which you do pay for what you don't use, both in memory usage and runtime.

But the STL now provides some handy alternatives — std::string_view and std::reference_wrapper<std::string>. Let's explore & benchmark them in this brief post.

A std::string owns a mutable & growable sequence of characters. It owns a char* to a null-terminated C-string, but must also hold the size since the standard requires that .size() takes constant time. It also has a capacity, much like std::vector, since it is often used to build strings iteratively.

Small string optimisation (SSO). When strings are small, they can be stored inside the std::string object itself, rather than as a separate memory allocation, managed by the std::string. This means that a string of length <= 22 (libc++) or 15 (libstdc++) can have no additional memory usage. Slightly abstracted, they look like this:

Take a std::string, remove its ability to grow (delete capacity), don't require the data to be null-terminated, make it non-owning, and you get a std::string_view. It's pretty straight forward:

Leave a Comment
Related Posts