std :: to_string vs stringstream

use*_*ser 5 c++ tostring stringstream c++11

下面的代码显示2种溶液(std::to_string和std::stringstream),该转换的int m_currentSoundTime到std::string.是更快std::to_string还是std::stringstream更快?

// Compute current sound time in minute and convert to string
stringstream currentTime;
currentTime << m_currentSoundTime / 60;
m_currentSoundTimeInMinute =  currentTime.str();
Run Code Online (Sandbox Code Playgroud)

要么

m_currentSoundTimeInMinute = to_string( m_currentSoundTime / 60 );
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 7

在任何合理的库实现to_string将至少快stringstream了这一点.但是,如果您想将10个整数放入字符串中,stringstream则可能会更快.如果你要做的to_string(a) + ", " + to_string(b) + /*...*/每一个操作可能会导致分配和从前一个字符串到新分配的副本 - 不是真的stringstream.

更重要的是,从您的示例代码中可以清楚地看出to_string,将单个 int转换为字符串更简洁.

  • @MatthieuM.是的但是来自`to_string(a)`的临时结果可能有一个`容量`_just_足够大,它目前持有的东西.因此,当你"+","`,即使你不需要额外的`string`临时,当前`string`拥有的分配需要重新制作更大,旧数据复制到新的分配,等等重复每个`+`.实现可以(应该)使用`realloc` ...但它会有同样的问题,不一致. (9认同)

Rob*_*nke 5

这篇博文测试了几种 int 到 string 的转换方法(在 Ubuntu 13.04 上使用 GCC 4.7)。在这种情况to_string下比 慢一些stringstream。但这可能很大程度上取决于编译器和标准库。