是否存在规范/公共/免费实现的变体,std::stringstream
其中我每次致电都不为完整的字符串副本付费str()
?(可能是通过c_str()
在osteam类中提供直接成员吗?)
我在这里发现了两个问题:
并且“当然”,不推荐使用的std::strstream
类确实允许直接缓冲区访问,尽管它的接口确实很古怪(除了不推荐使用)。
似乎还可以找到几个代码示例,这些示例确实说明了如何自定义std::streambuf
以允许直接访问缓冲区-我在实践中还没有尝试过,但是似乎很容易实现。
我的问题实际上有两个方面:
std::[o]stringstream
(或更确切地说,basic_stringbuf
)不允许直接缓冲区访问,而仅允许通过整个缓冲区的(昂贵的)副本进行访问?注:副本的表现打的str()
品牌是非常可测量的(*),所以它似乎不可思议不得不支付这时候使用情况我已经看到到目前为止真的从来没有需要从字符串流返回一个副本。(如果我需要一份副本,可以随时在“客户端”上进行。)
(*):使用我们的平台(VS 2005),我在发行版中衡量的结果是:
// tested in a tight loop:
// variant stream: run time : 100%
std::stringstream msg;
msg << "Error " << GetDetailedErrorMsg() << " while testing!";
DoLogErrorMsg(msg.str().c_str());
// variant string: run time: *** 60% ***
std::string msg;
((msg += "Error ") += GetDetailedErrorMsg()) += " while testing!";
DoLogErrorMsg(msg.c_str());
因此,使用std::string
with +=
(显然仅在不需要自定义/数字格式的情况下才有效,它比流版本快40%,据我所知,这仅是因为制作了完整的多余副本str()
。
至于第二弹
鉴于似乎很容易实现,但并非易事,是否可以通过boost或其他来源使用任何变体来打包此功能?
还有就是 了Boost.Iostreams,它甚至包含了一个例子如何实现的(O)用字符串流接收器。
我提出了一些测试实现来对其进行度量:
#include <string>
#include <boost/iostreams/stream.hpp>
#include <libs/iostreams/example/container_device.hpp> // container_sink
namespace io = boost::iostreams;
namespace ex = boost::iostreams::example;
typedef ex::container_sink<std::wstring> wstring_sink;
struct my_boost_ostr : public io::stream<wstring_sink> {
typedef io::stream<wstring_sink> BaseT;
std::wstring result;
my_boost_ostr() : BaseT(result)
{ }
// Note: This is non-const for flush.
// Suboptimal, but OK for this test.
const wchar_t* c_str() {
flush();
return result.c_str();
}
};
在我所做的测试中,将其与c_str()
辅助程序一起使用的速度比ostringstream
其复制str().c_str()
版本的普通工具快一些。
我不包括测量代码。该区域的性能非常脆弱,请确保自己衡量用例!(例如,字符串流的构造函数开销不可忽略。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句