Question
Should I compare a std::string to "string" or "string"s?
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.