As mentioned in the title, I'm looking for something that can give me more performance than atoi. Presently, the fastest way I know is
atoi(mystring.c_str())
Finally, I would prefer a solution that doesn't rely on Boost. Does anybody have good performance tricks for doing this?
Additional Information: int will not exceed 2 billion, it is always positive, the string has no decimal places in it.
Chrome 61.0. 3163. Number() is fastest of all. I just compared Number() to ~~ (just a few runs on jsben.ch), and Number() won, though sometimes it was nearly even.
Atoi is the fastest I could come up with. I compiled with msvc 2010 so it might be possible to combine both templates.
atoi is not deprecated, your source is incorrect. Nothing in the current C standard ISO 9899:2011 indicates this (see for example chapter 6.11 future language directions), nor anything in earlier standards. As per the C standard, atoi is equivalent to strtol as follows, C11 7.22.
atoi is the 'ascii to integer' function and itoa is the reverse, the 'integer to ascii' function.
I experimented with solutions using lookup tables, but found them fraught with issues, and actually not very fast. The fastest solution turned out to be the least imaginitive:
int fast_atoi( const char * str ) { int val = 0; while( *str ) { val = val*10 + (*str++ - '0'); } return val; }
Running a benchmark with a million randomly generated strings:
fast_atoi : 0.0097 seconds atoi : 0.0414 seconds
To be fair, I also tested this function by forcing the compiler not to inline it. The results were still good:
fast_atoi : 0.0104 seconds atoi : 0.0426 seconds
Provided your data conforms to the requirements of the fast_atoi
function, that is pretty reasonable performance. The requirements are:
INT_MAX
atoi
can be improved upon significantly, given certain assumptions. This was demonstrated powerfully in a presentation by Andrei Alexandrescu at the C++ and Beyond 2012 conference. Hi s replacement used loop unrolling and ALU parallelism to achieve orders of magnitude in perf improvement. I don't have his materials, but this link uses a similar technique: http://tombarta.wordpress.com/2008/04/23/specializing-atoi/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With