Benchmark String Conversion in C++
2020-01-24
I recently traced an underperforming routine in a C++ application to the construction of some strings from a stringstream used in this case to convert from an integer. This is a fairly common thing to see as stringstreams are flexible for converting from different types. Here’s an example of the operation I’m talking about.
#include <string>
#include <sstream>
int main()
{
std::string x("prefix ");
std::string y;
for (int i = 0; i < 10; ++i)
{
std::ostringstream oss;
<< x << " " << i;
oss = oss.str();
y }
}
First I could see that the stringstream did not need to be constructed in the loop, but also since C++11 we’ve had another way to do this using std::to_string
. Here’s the same task done this modern way, without stringstreams.
#include <string>
int main()
{
std::string x("prefix ");
std::string y;
for (int i = 0; i < 10; ++i)
{
= x + std::to_string(i);
y }
}
I expect this to be faster because it requires no construction in the loop and stringstreams are known to be slow, but how much faster? This is an example where I can quickly make and share a benchmark using Quick C++ Benchmark by Fred Tingaud.
The tool allows you to select different compilers, C++ standards and optimisation levels. It doesn’t support MSVC unfortunately, but Clang and GCC are available.
In summary, using to_string
is faster here than stringstream conversion and Quick C++ Benchmark is a useful tool for benchmarking C++ code.