【前言】
在C/C++编码中有大量的string、interger互转需求,系统接口要么不好用,要么性能不高。基于性能优化、个人兴趣两个主要目的,对string、integer互转优化做了大量的尝试,下面分享一下优化中的一些过程。
【优化效果概览】
32位环境(-O2):
[----------] 4 tests from performance
[ RUN ] performance.int32_to_str
fi2s int32 cost: 16765 us
snprintf int32 cost: 594351 us
!!!!!!!!!!!! fi2s(32) is 35.451894 times faster than snprintf
[ OK ] performance.int32_to_str (613 ms)
[ RUN ] performance.int64_to_str
fi2s int64 cost: 189455 us
snprintf int64 cost: 1625197 us
!!!!!!!!!!!! fi2s(64) is 8.578275 times faster than snprintf
[ OK ] performance.int64_to_str (1815 ms)
[ RUN ] performance.str_to_int32
fs2i int32 cost: 3763 us
atoi int32 cost: 77420 us
!!!!!!!!!!!! fs2i(32) is 20.574010 times faster than atoi
[ OK ] performance.str_to_int32 (81 ms)
[ RUN ] performance.str_to_int64
fs2i int64 cost: 5521 us
atoi int64 cost: 168755 us
!!!!!!!!!!!! fs2i(64) is 30.566021 times faster than atoll
[ OK ] performance.str_to_int64 (174 ms)
[----------] 4 tests from performance (2683 ms total)
64位环境(-O2):
[----------] 4 tests from performance
[ RUN ] performance.int32_to_str
fi2s int32 cost: 20086 us
snprintf int32 cost: 502266 us
!!!!!!!!!!!! fi2s(32) is 25.005775 times faster than snprintf
[ OK ] performance.int32_to_str (522 ms)
[ RUN ] performance.int64_to_str
fi2s int64 cost: 80195 us
snprintf int64 cost: 1261576 us
!!!!!!!!!!!! fi2s(64) is 15.731355 times faster than snprintf
[ OK ] performance.int64_to_str (1342 ms)
[ RUN ] performance.str_to_int32
fs2i int32 cost: 4471 us
atoi int32 cost: 67413 us
!!!!!!!!!!!! fs2i(32) is 15.077835 times faster than atoi
[ OK ] performance.str_to_int32 (72 ms)
[ RUN ] performance.str_to_int64
fs2i int64 cost: 5735 us
atoi int64 cost: 115071 us
!!!!!!!!!!!! fs2i(64) is 20.064690 times faster than atoll
[ OK ] performance.str_to_int64 (121 ms)
[----------] 4 tests from performance (2057 ms total)
【整数转字符串优化】
一般用系统接口snprintf(sprintf是高危函数,不考虑)来做整数转字符串的需求,用起来稍微有点麻烦,大致如下:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%d", 12345);