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

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

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

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

  1. type = int input_count = 1

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

2. type = int input_count> 30

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

cpp

std :: ostringstream oss;

oss.str(“”);

oss.clear();

```

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

3. type = double input_count = 1

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

3. type = double input_count = 30

对于多个输入,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值