paint-brush
std::string conversion benchmark in C++ by@asitdhal
4,901 reads
4,901 reads

std::string conversion benchmark in C++

by Asit Dhal
Asit Dhal HackerNoon profile picture

Asit Dhal

@asitdhal

software developer

October 22nd, 2017
Read on Terminal Reader
Read this story in a terminal
Print this story
Read this story w/o Javascript
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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

Company Mentioned

Mention Thumbnail
Google
featured image - std::string conversion benchmark in C++
1x
Read by Dr. One voice-avatar

Listen to this story

Asit Dhal HackerNoon profile picture
Asit Dhal

Asit Dhal

@asitdhal

software developer

About @asitdhal
LEARN MORE ABOUT @ASITDHAL'S
EXPERTISE AND PLACE ON THE INTERNET.

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

  1. std::to_string
  2. std::ostringstream
  3. boost::lexical_cast

image

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

image

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

image

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.

image

3. type=double input_count=1

image

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

3. type=double input_count=30

image

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

L O A D I N G
. . . comments & more!

About Author

Asit Dhal HackerNoon profile picture
Asit Dhal@asitdhal
software developer

TOPICS

THIS ARTICLE WAS FEATURED IN...

Permanent on Arweave
Read on Terminal Reader
Read this story in a terminal
 Terminal
Read this story w/o Javascript
Read this story w/o Javascript
 Lite
Aryan

Mentioned in this story

companies
X REMOVE AD