加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C 14中提高“str1 str2 str3 ……”的效率?

发布时间:2020-12-16 06:46:13 所属栏目:百科 来源:网络整理
导读:std::string Concatenate(const std::string s1,const std::string s2,const std::string s3,const std::string s4,const std::string s5){ return s1 + s2 + s3 + s4 + s5;} 默认情况下,返回s1 s2 s3 s4 s5;可能等同于以下代码: auto t1 = s1 + s2; // All
std::string Concatenate(const std::string& s1,const std::string& s2,const std::string& s3,const std::string& s4,const std::string& s5)
{
    return s1 + s2 + s3 + s4 + s5;
}

默认情况下,返回s1 s2 s3 s4 s5;可能等同于以下代码:

auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3

return t3 + s5; // Allocation 4

有一种优雅的方法可以将分配时间减少到1吗?我的意思是保持返回s1 s2 s3 s4 s5;没有改变,但效率自动提高.如果可能的话,它也可以避免程序员误用std :: string :: operator.

ref-qualifier成员函数有帮助吗?

解决方法

问题的前提是:

s1 + s2 + s3 + s4 + s5 + ... + sn

将要求n分配不正确.

相反,它将需要O(Log(n))分配.第一个s1 s1将生成一个临时的.随后,临时(rvalue)将成为所有后续操作的左参数.该标准指定当字符串的lhs是rvalue时,该实现只是附加到该临时值并将其移出:

operator+(basic_string<charT,traits,Allocator>&& lhs,const basic_string<charT,Allocator>& rhs);

Returns: std::move(lhs.append(rhs))

该标准还规定了字符串的容量将在几何上增长(通常在1.5和2之间).因此,在每次分配时,容量将以几何方式增长,并且该容量沿着操作链传播.更具体地说,原始代码:

s = s1 + s2 + s3 + s4 + s5 + ... + sn;

实际上相当于:

s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;

当几何容量增长与短串优化相结合时,“预先保留”正确容量的值是有限的.如果这样的代码实际上显示为性能测试中的热点,我只会费心去做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读