考虑这个代码片段:
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 https://godbolt.org/z/fIppl1, 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()
,所以在这种情况下当然不会进行就地施工。因此删除下面的一些行。)
但是,看看罢工>
所有比较均通过compare()
成员函数。
根据我的理解,这意味着我们需要构建一个std::string
无论如何,为了执行比较,所以我怀疑开销最终会是相同的(尽管通过调用隐藏operator==
).
Neither.
如果你想变得聪明,就比较一下"string"sv https://en.cppreference.com/w/cpp/string/basic_string_view/operator%22%22sv,它返回一个std::string_view https://en.cppreference.com/w/cpp/string/basic_string_view.
与字面意思比较时"string"
不会导致任何分配开销,它被视为空终止字符串,并具有所有伴随的缺点:不能容忍嵌入的空值,并且用户必须注意空终止符。
"string"s
进行分配,除非小字符串优化 https://stackoverflow.com/questions/56425276/inconsistent-behavior-of-compiler-optimization-of-unused-string or 分配省略 https://stackoverflow.com/questions/31873616/is-the-compiler-allowed-to-optimize-out-heap-memory-allocations。此外,运算符会传递文字的长度,无需计数,并且它允许嵌入空值。
最后使用"string"sv
结合了其他两种方法的优点,避免了各自的缺点。也std::string_view
是一个比a简单得多的野兽std::string
,特别是如果后者像所有现代的那样使用 SSO。
至少从 C++14(通常允许省略分配)开始,理论上,只要有足够的信息(通常可用于示例)和努力,编译器就可以将所有选项优化到最后一个选项。假设规则 https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule。但我们还没有到那里。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)