Boost logo

Boost :

Subject: [boost] [lexical_cast] efficiency
From: Domagoj Saric (dsaritz_at_[hidden])
Date: 2010-01-18 03:30:18


'A while back', in the "error_code debate" I used a lexical_cast<> example for
demonstrating certain concerns/aspects but the whole post was so long (as usual
:) that it was probably read by less than 0.1% of people :)
Anyways I'm extracting and reposting this bit now as I think it warrants
attention.

The first problem is the ('standard') "std::streams vs efficency" issue:
 - on msvc 9.0 sp1 the single line
   boost::lexical_cast<int>( "321" );
caused 14 calls to new and 26 calls to EnterCriticalSection() (not to mention
vtable initializations, virtual function calls, usage of locales...) the
first time it is called, and 3 calls to new and 15 calls to
EnterCriticalSection() on subsequent calls...It also caused the binary (which
does not otherwise use streams) to increase by 50 kB! ...which is IMNHO
abhorrent...
(with my usual 'put things in perspective' examples
http://www.theprodukkt.com/kkrieger http://www.youtube.com/watch?v=3vzcMdkvPPg
:)

As a start maybe this problem could be sufficiently "lessened" by providing
lexical_cast specializations/overloads that use C library functions (strtol,
itoa and the likes) as they suffer less from bloat/performance issues than
std::streams. Ideally, IMHO, lexical_cast<> should provide the
power/configurability of boost::numeric_cast (so that one can, for example, say
I do not need/want to use locales/assume ASCII strings and things like that).

The second problem is the use of exceptions (or better of only using
exceptions):
if, for example, one uses lexical_cast<> deep in the bowels of some parser it
is probably "natural" to use a bad_cast exception to report an error to
the outside world but if one uses lexical_cast<> to convert a string entered
into a widget by a user into an int it would mostly be simpler to have a simple
error code if the user entered an invalid string and issue a warning and retry
"at the face of the place" (without the need for try-catch blocks)... In other
words maybe a dual/hybrid approach of using both exceptions and error codes
(through different overloads would be justified).

-- 
 "That men do not learn very much from the lessons of history is the most
important of all the lessons of history."
 Aldous Huxley

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk