对于字符串对象连接,stringstream是否比string的运算符'+'更好?

cwf*_*ter 9 c++ string

例如,我有两个字符串对象:string str_1,str_2.我想连接他们.我可以使用两种方法:方法1:

std::stringstream ss;
//std::string str_1("hello");
//std::string str_2("world");
ss << "hello"<< "world"?
const std::string dst_str = std::move(ss.str());
Run Code Online (Sandbox Code Playgroud)

方法2:

std::string str_1("hello");
std::string str_2("world");
const std::string dst_str = str_1 + str_2;
Run Code Online (Sandbox Code Playgroud)

因为字符串的缓冲区是只读的,所以当您更改字符串对象时,其缓冲区将销毁并创建一个新的缓冲区来存储新内容.方法1比方法2好吗?我的理解是否正确?

Chr*_*phe 8

stringstreams与简单的字符串相比是复杂的对象.每一天你使用方法1,stringstream必须构造,然后破坏.如果你这样做了数百万的时间,那么开销将远远不能忽视.

显然简单ss << str_1 << str_2实际上相当于std::operator<<(sst::operator<<(ss, str_1), str_2);没有针对内存连接进行优化,但对所有都是通用的.

我做了一个小基准测试:

  • 在调试模式下,方法2的速度几乎是method1的两倍.

  • 在优化的构建中(在汇编程序文件中验证没有进行任何优化),它的速度提高了27倍.