There are two ways to convert any fundamental data to string.

std::to_string std::ostringstream boost::lexical_cast

In this post, I will analyze which one is the fastest to convert any fundamental data to string. I am using google benchmark to measure the time difference. In all charts, y-axis is time in nano seconds and x-axis is both real time and cpu time.

type=int input_count = 1

For only, one conversion, both std::stringstream and std::ostringstream take nearly same time. boost::lexical_cast in the fastest. And std::to_string is in between.

2. type=int input_count > 30

Here both std::stringstream and std::ostringstream outperform std::to_string and boost::lexical_cast. You can get better result by reusing std::stringstream and std::ostringstream buffer.

```cpp

std::ostringstream oss;

oss.str(“”);

oss.clear();

```

Creating stream objects are very expensive. So, reuse of buffer gives better result.

3. type=double input_count=1

Performance is very similar to integer. Boost lexical_cast outperforms everyone.

3. type=double input_count=30

For multiple inputs, boost::lexical_cast outperforms everyone else.

So, my observations are

Always use std::to_string to convert any single value to std::string.

In case of double, use std::string. If you need, precision, use std::ostringstream.

In all other cases, use std::ostringstream.

Prefer boost::lexical_cast if you have boost in your project

Image produced: https://github.com/asit-dhal/BenchmarkViewer