What’s the fastest way to convert a string represented by (const char*, size_t) to an int?
The string is not null-terminated.
Both these ways involve a string copy (and more) which I’d like to avoid.
And yes, this function is called a few million times a second. :p
int to_int0(const char* c, size_t sz)
{
return atoi(std::string(c, sz).c_str());
}
int to_int1(const char* c, size_t sz)
{
return boost::lexical_cast<int>(std::string(c, sz));
}
Fastest:
Since in the above code, the comparison
(s[0] == '-')is done in every iteration, we can avoid this by calculatingresultas negative number in the loop, and then returnresultifs[0]is indeed'-', otherwise return-result(which makes it a positive number, as it should be):That is an improvement!
In C++11, you could however use any function from
std::stoifamily. There is alsostd::to_stringfamily.