Can anyone beat the performance of my integer to std::string code, linked below?
There are already several questions that explain how to convert an integer into a std::string
in C++, such as this one, but none of the solutions provided are efficient.
Here is compile-ready code for some common methods to compete against:
Contrary to popular belief, boost::lexical_cast
has its own implementation (white paper) and does not use stringstream
and numeric insertion operators. I'd really like to see its performance compared, because this other question suggests that it's miserable.
And my own contribution, which is competitive on desktop computers, and demonstrates an approach that runs at full speed on embedded systems as well, unlike algorithms dependent on integer modulo:
If you want to use that code, I'll make it available under a simplified BSD license (commercial use allowed, attribution required). Just ask.
Finally, the function ltoa
is non-standard but widely available.
I'll post my performance measurements as an answer shortly.
std::string
.INT_MIN
on a two's complement machine where the absolute value is not representable.stringstream
, http://ideone.com/jh3Sa, but anything that is clearly understandable as the correct number is ok, too.Besides better algorithms, I'd also like to get some benchmarks on several different platforms and compilers (let's use MB/s throughput as our standard unit of measure). I believe that the code for my algorithm (I know the sprintf
benchmark takes some shortcuts -- now fixed) is well-defined behavior by the standard, at least under the ASCII assumption, but if you see any undefined behavior or inputs for which the output is invalid, please point that out.
Different algorithms perform for g++ and VC2010, likely due to the different implementations of std::string
on each. VC2010 clearly does a better job with NRVO, getting rid of return-by-value helped only on gcc.
Code was found that outperforms sprintf
by an order of magnitude. ostringstream
falls behind by a factor of 50 and more.
The winner of the challenge is user434507 who produces code that runs 350% of the speed of my own on gcc. Further entries are closed due to the whims of the SO community.
The current (final?) speed champions are:
sprintf
: http://ideone.com/0uhhXsprintf
: http://ideone.com/VpKO3