(There is also an opposite string-to-int performance test.)
(Updated 2011-02-05: Added a hand-made function as baseline; re-run all tests, and with new clang++ from svn)

A performance benchmark of which method is faster of converting an integer to an std::string. The goal is ending up with an std::string representation of the input integer.

The tested methods are:

  • naive loop into a std::string
  • sprintf() into a char[] buffer, then std::string(buffer)
  • snprintf() into a char[] buffer, then std::string(buffer)
  • sprintf() into &std::string[0], and .resize() to fit
  • snprintf() into &std::string[0], and .resize() to fit
  • output to a std::stringstream, then std::string = stream.str()
  • as above, but reusing the stringstream object
  • std::strstream(&string[0]) then .resize(stream.pcount())
  • std::string = boost::lexical_cast<std::string>()
  • Boost.Spirit.Karma generate into a char[] buffer, then std::string(buffer)

Source for the test is at speed-convert-int-to-string.cpp with cycle.h.

The compilers are Microsoft Visual C++ 2010 Express as VC10 with _SECURE_SCL disabled, GNU g++ 4.4.1, and clang++ from svn.

Continue Reading »