考虑以下代码片段:
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
}
乍一看,与const char*
进行比较似乎需要更少的汇编指令1,因为使用字符串字面值将导致std::string
的原地构建。(编辑:正如答案中指出的那样,我忘记了实际上在
foo()
中将调用s.compare(const char*)
,因此在这种情况下不会发生原地构建。因此划掉下面的一些行。)然而,看着
operator==(const char*, const std::string&)
参考:
据我理解,这意味着我们将需要构造一个所有比较都通过
compare()
成员函数进行。
std::string
来执行比较,因此我怀疑最终的开销将是相同的(虽然被operator==
的调用隐藏)。
- 我应该选择哪个比较?
- 是否有一个版本比另一个版本更具优势(可能在特定情况下)?
-O2/3
进行比较,我的意思是谁会在调试版本中关心指令的数量呢?;) - 463035818_is_not_a_numberconst A
或const A&
。 - andreee