Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Is std::to_string or std::stringstream faster?

// 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 );
like image 856
user Avatar asked Oct 17 '13 14:10

user


People also ask

Is Stringstream slow C++?

string stream is slow. Quite very slow. If you are writing anything performance critical that acts on large data sets ( say loading assets after a level change during a game ) do not use string streams.

What library is To_string?

C++ Bitset Library - to_string() Function.

What is the function of To_string?

The toString() method returns a string representing the source code of the specified Function .


2 Answers

In any reasonable library implementation to_string will be at least as fast as stringstream for this. However, if you wanted to put 10 ints into a string, stringstream will likely be faster. 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.

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.

like image 166
David Avatar answered Sep 27 '22 19:09

David


This blog post tests several int-to-string conversion methods (using GCC 4.7 on Ubuntu 13.04). In this case to_string is somewhat slower than stringstream. But this probably depends strongly on the compiler and std library.

like image 43
Robert Franke Avatar answered Sep 27 '22 18:09

Robert Franke