folly源码分析(1) - Conv.h

本文探讨了Facebook的Folly库中Conv模块,它提供了比snprintf和strtol更快的整数与字符串之间的转换。重点分析了int转string的查表操作以及string转int的差别操作,实验显示Folly的转换性能显著优于传统方法。
摘要由CSDN通过智能技术生成

Conv是一个类型转换的库,主要实现了字符串到整数和浮点数的转换,性能要比snprintfstrtol要好上一些。

doublestring的来回转换主要是用google的开源项目double conversion来实现的,这里按下不表

我们主要考察intstring的来回转换的实现

其中int->string的关键代码是,可以看到是非常简单的查表操作:

extern const chardigit1[101] =
 "00000000001111111111222222222233333333334444444444"
 "55555555556666666666777777777788888888889999999999";
extern const chardigit2[101] =
 "01234567890123456789012345678901234567890123456789"
 "01234567890123456789012345678901234567890123456789";
 
// Returns the offset ofthe formatted string from the start of
// the supplied buffer.The new string will be at range
//[buf+begin,buf+bufLen). Uint will be either uint32_t or uint64_t.
template <classUint>
size_tuintToBuffer(char*const buffer, size_t bufLen, Uint v) {
  extern const char digit1[101], digit2[101];
  for (;;) {
    if (v < 100) {
      if (v < 10) {
        buffer[--bufLen] =static_cast<char>(v + '0');
      } else {
        size_t r =static_cast<size_t>(v);
        bufLen -= 2;
        buffer[bufLen] = digit1[r];
        buffer[bufLen + 1] = digit2[r];
      }
      break;
    }
    Uint t = v;
    v /= 100;
    size_t r = static_cast<size_t> (t - v* 100);
    bufLen -= 2;
    buffer[bufLen] = digit1[r];
    buffer[bufLen + 1] = digit2[r];
  }
  return bufLen;
}


性能:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值