C++ 07 Feb 2010 15:41:15

(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.



Tests were run for converting 100000 integers in the range -50000 to 50000. The result for a hand-made naive function is set as the baseline 100% and the other numbers is time spent relative to that.

Boost.Spirit.Karma is by far the fastest. It is also worth noting that reusing the string object makes the boost::lexical_cast solution slower, presumably because it ruins some optimization opportunities, so that is a case for checking whether reusing your objects really is faster…

Windows: MSVC++ 2010 Express

Compiler: MSVC++ 2010 _SECURE_SCL=0

Arch: Windows 7 64 bit, 1.60GHz Core i7 Q720, 8 GiB RAM

Linux: GNU g++ 4.4.1

Compiler: GNU g++ 4.4.1 -std=c++0x -O3

Arch: Linux 2.6.27 x86_64, 2.66GHz Xeon, 8 GiB RAM

Linux: LLVM clang++

[table "7" seems to be empty /][table "8" seems to be empty /][table "11" seems to be empty /]