This google-benchmark code checked on Quick Bench, shows that string::empty()
runs a lot faster than comparing with an empty-string literal. However, creating a name string of ""
actually makes the compiler optimize away the check:
bool compareWithNamedConst(const std::string& target) { const std::string emptyString = ""; return emptyString == target;}bool compareWithLiteral(const std::string& target) { return "" == target;}bool compareWithRvalue(const std::string& target) { return std::string{""} == target;}bool checkForEmpty(const std::string& target) { return target.empty();}
The performance for each of the calls is shown here:
As you can see, comparing with ""
is very slow compared to all the other options. I wonder why it is the case? It must be somehow related to SSO not being applied on const char*
, as testing this:
bool compareWithLiteral(const std::string& target) { return "test with a longer string not optimized" == target;}bool compareWithRvalue(const std::string& target) { return std::string{"test with a longer string not optimized"} == target;}
Results comparing with a literal actually being faster:
I find that checking for string emptiness, the easiest syntax to read is "" == myVariable
as it clearly indicates that myVariable
is a std::string
with no unneccesary clutter. Why can't we have it optimized as we have all the other cases?