Monday, December 20, 2004

C++ Convert int to string

On my current project at work, we have been focusing on speed. Its interesting to think about how many microseconds (or nanoseconds) it takes to do something. I hope to post over the next few weeks some performance comparisons between various techniques in C++.

My laptop which I'll be running the tests on is a Mobile Intel Pentium 4M 2200 MHz with 768 MB DDR SDRAM. I'll be compiling with Microsoft Visual C++ 7.1 in release mode. The tests are simple iteration tests running the same code over and over again a 1000 times. I know that this is not representative of real performance do to caching affects, but even this simple testing can be eye opening.

Today lets look at boost::lexical_cast. We use boost and ACE on our current project. lexical_cast is a way of converting between strings and other types (actually it is a generic way of converting to/from more than just strings). So if I wanted to convert 23 to "23" I can do this:

std::string twentythree = boost::lexical_cast(23);

If I do this on my laptop it runs in about 7 microseconds. Not too bad. However, if I use a C approach and do the following:

char buf[20];
ACE_OS::sprintf(buf, "%d", 23);

It runs in 0.3 microseconds, which, I think you would agree, is better.

The lexical_cast is safer and more general but is it worth the difference? I would say it depends.

So why is lexical_cast so much slower? Well, its because it uses std::stringstream. Take a look at the following:

std::stringstream ss;
ss << 23;

The above takes 6.7 microseconds, which is clearly most of the effort of lexical_cast.

1 comment:

Anonymous said...

That was exactly the technical level I was looking for, thank you!