我应该将std :: string与“ string”进行比较吗?或“字符串”? [英] Should I compare a std::string to "string" or "string"s?
问题描述
考虑以下代码段:
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
的就地构造。
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
.
(编辑:正如答案中指出的那样,我忘记了有效地 s.compare(const char *)
将在 foo()
中调用,因此在这种情况下当然不会进行就地构造。因此,请在下面删除一些行。)
( 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.)
但是,请查看 operator ==(const char *,const std :: string&)
参考:
所有比较都是通过
compare()
mem完成的ber函数。
All comparisons are done via the
compare()
member function.
根据我的理解,这意味着我们将需要构建 std :: string
还是为了进行比较,所以我怀疑最终的开销是一样的(尽管对 operator == 的调用隐藏了)
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==
).
- 我应该选择哪个比较?
- 一个版本是否有相对于其他优点(可能在特定情况下)?
1 较少的汇编指令并不一定意味着更快的代码,但我不想在这里进行微基准测试。
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.
推荐答案
都不是。
如果您想变得聪明一点,请与 字符串 sv
,它返回 std :: string_view
。
与类似的文字进行比较字符串
不会导致任何分配开销,它被视为以null结尾的字符串,具有所有伴随的缺点:不能容忍嵌入的null,用户必须注意
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
进行分配,除非小型字符串优化或分配选择。而且,运算符可以传递文字的长度,无需计数,并且允许嵌入空值。
"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.
最后使用 string sv
结合了其他两种方法的优点,避免了它们各自的缺点。另外, std :: string_view
是比 std :: string
简单得多的野兽,尤其是如果后者使用
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.
至少自C ++ 14(通常允许省略分配)以来,编译器理论上可以优化该选项的所有选项。最后一个,在视情况而定。但是我们还没有。
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.
这篇关于我应该将std :: string与“ string”进行比较吗?或“字符串”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!