user
user

Reputation: 301

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 );

Upvotes: 6

Views: 11574

Answers (2)

Robert Franke
Robert Franke

Reputation: 2374

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.

Upvotes: 5

David
David

Reputation: 28178

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.

Upvotes: 7

Related Questions