45

Consider this code snippet:

bool foo(const std::string& s) {
    return s == "hello"; // comparing against a const char* literal
}

bool bar(const std::string& s) {
    return s == "hello"s; // comparing against a std::string literal
}

At first sight, it looks like comparing against a const char* needs less assembly instructions1, as using a string literal will lead to an in-place construction of the std::string.

(EDIT: As pointed out in the answers, I forgot about the fact that effectively s.compare(const char*) will be called in foo(), so of course no in-place construction takes place in this case. Therefore striking out some lines below.)

However, looking at the operator==(const char*, const std::string&) reference:

All comparisons are done via the compare() member function.

From my understanding, this means that we will need to construct a std::string anyway in order to perform the comparison, so I suspect the overhead will be the same in the end (although hidden by the call to operator==).

  • Which of the comparisons should I prefer?
  • Does one version have advantages over the other (may be in specific situations)?

1 I'm aware that less assembly instructions doesn't neccessarily mean faster code, but I don't want to go into micro benchmarking here.

8
  • 9
    return s == "hello";.
    – molbdnilo
    Jun 3, 2019 at 12:48
  • 4
    better use -O2/3 for the comparison, i mean who cares how many instructions it is in a debug build ? ;) Jun 3, 2019 at 12:48
  • 7
    @Someprogrammerdude No it isn't. It's a case of not writing needlessly wasteful code. The choice between a string literal and a needless string instantiation is not a micro optimisation; it's common sense! In other words, this is about writing good code. Jun 3, 2019 at 12:48
  • 9
    There is too much bloaty and slow code in the world at the moment because people consider writing good code that doesn't do more that it needs to, to be "premature optimisation" and have been scared away from thinking about the code they're writing as a result :( Jun 3, 2019 at 12:51
  • 4
    @Someprogrammerdude this doesn't have anything to do with premature optimization, I'm asking out of curiosity in the first place and also this would affect coding style to some extent. You don't tell people to pass const A vs. const A& in the general case just because they shouldn't care about "premature optimization"
    – andreee
    Jun 3, 2019 at 12:53

3 Answers 3

67

Neither.

If you want to be clever, compare to "string"sv, which returns a std::string_view.


While comparing against a literal like "string" does not result in any allocation-overhead, it's treated as a null terminated string, with all the concomittant disadvantages: No tolerance for embedded nulls, and users must heed the null terminator.

"string"s does an allocation, barring small-string-optimisation or allocation elision. Also, the operator gets passed the length of the literal, no need to count, and it allows for embedded nulls.

And finally using "string"sv combines the advantages of both other approaches, avoiding their individual disadvantages. Also, a std::string_view is a far simpler beast than a std::string, especially if the latter uses SSO as all modern ones do.


At least since C++14 (which generally allowed eliding allocations), compilers could in theory optimise all options to the last one, given sufficient information (generally available for the example) and effort, under the as-if rule. We aren't there yet though.

17
  • 3
    @xception Yes there is. Unfortunately the standard talks about newer overloads like that in incredibly arcane terms for very little good reason (rather than the good old-fashioned method of just listing overloads and their simple arguments). But it's 7-9 here that you're looking for. Jun 3, 2019 at 12:53
  • 6
    Sorry what's the benefit of this over a simple string literal? Don't get me wrong, I love string views and make judicious use of them when appropriate, but I'm not seeing it here. Jun 3, 2019 at 12:55
  • 7
    in fact, with -O3 gcc seems even to be able to inline the call to compare, which doesn't happen with the regular string literal. Jun 3, 2019 at 13:00
  • 10
    @LightnessRacesinOrbit There is no strlen() for creating the string_view using operator "" sv. Jun 3, 2019 at 13:01
  • 4
    Using string_view looks the fastest on gcc9.1 -Ofast because of inlining the call to compare. With -Os both string_view and string literal version call memcmp.
    – KamilCuk
    Jun 3, 2019 at 13:03
15

No, compare() does not require construction of a std::string for const char* operands.

You're using overload #4 here.

The comparison to string literal is the "free" version you're looking for. Instantiating a std::string here is completely unnecessary.

12
  • 1
    "Free" only if the implementation of the suitable compare function doesn't itself create a std::string object (although that's probably very unlikely). Jun 3, 2019 at 12:51
  • 5
    @Someprogrammerdude Free at this level of abstraction, yes. Theoretically the implementation could be designed to hive off the comparison to the cloud, resulting in multi-millisecond latency and potentially a login to Facebook - but let's be real ;) Jun 3, 2019 at 12:52
  • (However that is indeed why I used quotes cos nothing's truly free really) Jun 3, 2019 at 12:57
  • Hm, maybe I am missing/overlooking something here but how does it not need to construct a std::string if compare is a member function (non-static)?
    – andreee
    Jun 3, 2019 at 12:59
  • 1
    Okay I see. "The comparison to string literal is the "free" version you're looking for.": By string literal you seem to be talking about plain old C literals, while I was thinking of std::string_literals. This might be the problem :-)
    – andreee
    Jun 3, 2019 at 14:12
9

From my understanding, this means that we will need to construct a std::string anyway in order to perform the comparison, so I suspect the overhead will be the same in the end (although hidden by the call to operator==).

This is where that reasoning goes wrong. std::compare does not need to allocate its operand as a C-style null-terminated string to function. According to one of the overloads:

int compare( const CharT* s ) const; // (4)

4) Compares this string to the null-terminated character sequence beginning at the character pointed to by s with length Traits::length(s).

Although whether to allocate or not is an implementation detail, it does not seem reasonable that a sequence comparison would do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.