是std :: stringstream比std :: string更好的累积吗? [英] Is std::stringstream better to accumulate than std::string?

查看:224
本文介绍了是std :: stringstream比std :: string更好的累积吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 std :: stringstream 的优点之一是它是一个 std :: istream 因此它可以接受来自定义运算符< std :: istream 的任何类型的输入,原始类型。

I know one of the advantages of the std::stringstream is that it is a std::istream so it may accept input from any type that defines operator<< to std::istream, and also to the primitives type.

我不打算使用运算符<< ,我只是要连接很多字符串。 std :: stringstream 的实现是否使得它比 std :: string 更快,以连接很多字符串? / p>

I am not going to use the operator<<, I am just going to concatenate a lot of strings. Does the implementation of std::stringstream make it faster than std::string to concatenate a lot of strings?

推荐答案

没有理由期望 std :: string stringstream 的插入函数慢。 std :: string 通常只是一个可能的内存分配/复制,加上将数据复制到内存中。 stringstream 必须处理诸如locales等等,甚至是基本的调用。

There's no reason to expect std::string's appending functions to be slower than stringstream's insertion functions. std::string will generally be nothing more than a possible memory allocation/copy plus copying of the data into the memory. stringstream has to deal with things like locales, etc, even for basic write calls.

此外, std :: string 提供了最小化或消除第一次内存分配的方法。如果你保留足够的空间,每个插入只是一个 memcpy 。这不是真正可能的 stringstream

Also, std::string provides ways to minimize or eliminate anything but the first memory allocation. If you reserve sufficient space, every insertion is little more than a memcpy. That's not really possible with stringstream.

即使它比 std :: string 的附加函数,您仍然可以从 stringstream 中复制字符串来执行操作。这是另一个分配+副本,你不需要 std :: string

Even if it was faster than std::string's appending functions, you still have to copy the string out of the stringstream to do something with it. So that's another allocation + copy, which you won't need with std::string.

std :: stringstream 如果您需要格式,而不仅仅是将一些字符串粘在一起。

You should use std::stringstream if you need formatting, not just for sticking some strings together.

这篇关于是std :: stringstream比std :: string更好的累积吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆