Search code examples
c++c++17string-view

hash<std::string> vs hash<std::string_view>


C++17 introduced hash<string_view>. When writing my own custom hashes I want to reuse the STL implementation of the string hash.

Is std::hash<std::string>()("Hello, world") slower than std::hash<std::string_view>()("Hello, world")? Is it the same?

When do I ever want to use std::hash<std::string>()?


Solution

  • std::hash<std::string> takes a std::string const& as the parameter for its operator(). If you have std::string's, and you are hashing them, then this what you want. If you use hash<string_view> then it is going to have to convert the std::string into a std::string_view, which has some cost to it (not much, but it is there).

    If your data set doesn't contain just std::strings but also contains c-strings, then hash<string_view> can be better. converting a c-string into a std::string can require dynamic memory allocation so if you can avoid that normally you win in the performance area. This needs profiling though since the mix of std::strings and c-strings matter as well as the size of the c-strings as SSO (short string optimization) may make std::hash<std::string> the better choice.