views:

65

answers:

2

In the answer to this question ovanes states:

Please be aware that boost::lexical_cast is much slower as atoi. I also use it very often in a performance non-critical code. The problem with lexical_cast is that it uses stringstream for conversion. If you are working in a multi-threaded environement any stream class from the standard lib will use locks on a mutex for every character being inserted, even if the stream object is used from a single thread.Your number consisting of 17 chars will involve 17 mutex locks when put into stream. – ovanes Jun 22 at 11:59

Which begs the question, when do <iostream> objects lock a mutex? Is this true for objects from <sstream> as well? If so can this be prevented?

+3  A: 

The current C++ standard (C++03) does not contain anything about multi-threading.

Because of this, how a library uses mutexes would depend on the specific implementation.

R Samuel Klatchko
A: 

The issue with string_stream is that it is quite heavy. And it is not related to Mutexes.

And I'll explain why:

  • stringstream uses generic interface to access underlying buffer, same as used for files or for console access: a set of virtual functions. It is slower then iterating over char *
  • it Uses locale information so you may actually parse string that depends on type of thousands separators or different types of digits that are fetched for other class in locale interface.
  • And finally it calls atoi to convert the string to number.

lexical_cast is very powerful because it allows to cast any value and not integer only as done with atoi but with power comes prices.

Second thing, I don't think that any string_buffer implementation uses mutexes. File stream has sense in it but not string stream.

Artyom