std :: to_string vs stringstream

时间:2013-10-17 14:29:54

标签: c++ c++11 tostring stringstream

以下代码显示了将std::to_string std::stringstream转换为int的2个解决方案(m_currentSoundTimestd::string)。 std::to_stringstd::stringstream更快?

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

m_currentSoundTimeInMinute = to_string( m_currentSoundTime / 60 );

2 个答案:

答案 0 :(得分:6)

在任何合理的库中,实现to_string 至少与此stringstream一样快。但是,如果您想将10个整数放入字符串中,stringstream可能会更快。如果您要执行to_string(a) + ", " + to_string(b) + /*...*/,则每个操作都可能导致分配以及从前一个字符串到新分配的副本 - 与stringstream不一致。

更重要的是,从您的示例代码中可以明显看出to_string对于将单个 int转换为字符串更加清晰。

答案 1 :(得分:2)

这个blog post测试了几种int-to-string转换方法(在Ubuntu 13.04上使用GCC 4.7)。在这 case to_stringstringstream慢一些。但这可能很大程度上取决于编译器和std库。