std::string conversion benchmark in C++

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

  1. std::to_string
  2. std::ostringstream
  3. 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.

  1. 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.

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:

C++11/14, Qt, Juce

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store