简体   繁体   English

std :: to_string vs stringstream

[英]std::to_string vs stringstream

The code below shows 2 solutions ( std::to_string and std::stringstream ) that convert an int m_currentSoundTime to std::string . 下面的代码显示了将int m_currentSoundTime转换为std::string 2个解决方案( std::to_stringstd::stringstream )。 Is std::to_string or std::stringstream faster? std::to_stringstd::stringstream更快吗?

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

or 要么

m_currentSoundTimeInMinute = to_string( m_currentSoundTime / 60 );

In any reasonable library implementation to_string will be at least as fast as stringstream for this. 在任何合理的库实现中, to_string 至少stringstream一样快。 However, if you wanted to put 10 ints into a string, stringstream will likely be faster. 但是,如果你想将10个整数放入一个字符串中, stringstream可能会更快。 If you were to do to_string(a) + ", " + to_string(b) + /*...*/ every operation would probably cause an allocation and a copy from the previous string to the new allocation - not true with stringstream . 如果你要做to_string(a) + ", " + to_string(b) + /*...*/每个操作都可能导致分配和从前一个字符串复制到新的分配 - 对于stringstream不正确。

More importantly, it's pretty obvious from your example code that to_string is cleaner for dealing with converting a single int to a string. 更重要的是,从您的示例代码中可以明显看出, to_string对于处理将单个 int转换为字符串更加清晰。

This blog post tests several int-to-string conversion methods (using GCC 4.7 on Ubuntu 13.04). 这篇博客文章测试了几种int-to-string转换方法(在Ubuntu 13.04上使用GCC 4.7)。 In this case to_string is somewhat slower than stringstream . 在这种情况下, to_stringstringstream慢一些。 But this probably depends strongly on the compiler and std library. 但这可能很大程度上取决于编译器和std库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM