C ++中的std :: string转换基准

有两种方法可以将任何基本数据转换为字符串。

  1. std :: to_string
  2. std :: ostringstream
  3. boost :: lexical_cast
C ++中的std :: string转换基准

在本文中,我将分析将所有基本数据转换为字符串最快的方法。 我正在使用Google 基准来衡量时差。 在所有图表中,y轴是以纳秒为单位的时间,x轴是实时和cpu时间。

  1. type = int input_count = 1
C ++中的std :: string转换基准

仅一次转换 ,std :: stringstream和std :: ostringstream几乎都花时间。 以最快的速度进行boost :: lexical_cast。 并且std :: to_string在两者之间。

2. type = int input_count> 30

C ++中的std :: string转换基准

在这里,std :: stringstream和std :: ostringstream都胜过std :: to_string和boost :: lexical_cast。 通过重用std :: stringstream和std :: ostringstream缓冲区,可以获得更好的结果。

cpp

std :: ostringstream oss;

oss.str(“”);

oss.clear();

```

创建流对象非常昂贵。 因此,缓冲区的重用可以带来更好的结果。

C ++中的std :: string转换基准

3. type = double input_count = 1

C ++中的std :: string转换基准

性能与整数非常相似。 Boost lexical_cast的表现优于所有人。

3. type = double input_count = 30

C ++中的std :: string转换基准

对于多个输入,boost :: lexical_cast的表现优于其他所有人。

所以,我的观察是

  • 始终使用std :: to_string将任何单个值转换为std :: string。
  • 如果为double,请使用std :: string。 如果需要精度,请使用std :: ostringstream。
  • 在所有其他情况下,请使用std :: ostringstream。
  • 如果您的项目中有boost,则最好使用boost :: lexical_cast

产生的图像: https : //github.com/asit-dhal/BenchmarkViewer

From: https://hackernoon.com/string-conversion-benchmark-in-modern-c-48bb39079a07