Hackernoon logostd::string conversion benchmark in C++ by@asitdhal

std::string conversion benchmark in C++

Author profile picture

@asitdhalAsit Dhal

software developer

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;




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


The Noonification banner

Subscribe to get your daily round-up of top tech stories!