有两种方法可以将任何基本数据转换为字符串。
- std :: to_string
- std :: ostringstream
- boost :: lexical_cast
在本文中,我将分析将所有基本数据转换为字符串最快的方法。 我正在使用Google 基准来衡量时差。 在所有图表中,y轴是以纳秒为单位的时间,x轴是实时和cpu时间。
- 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