Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22032

Why is there no optimization for checking for empty string via "" comparison?

$
0
0

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?


Viewing all articles
Browse latest Browse all 22032

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>