Conv是一个类型转换的库,主要实现了字符串到整数和浮点数的转换,性能要比snprintf和strtol要好上一些。
double和string的来回转换主要是用google的开源项目double conversion来实现的,这里按下不表
我们主要考察int和string的来回转换的实现
其中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;
}
性能: