Very poor boost::lexical_cast performance

后端 未结 9 1034
别那么骄傲
别那么骄傲 2020-11-27 10:31

Windows XP SP3. Core 2 Duo 2.0 GHz. I\'m finding the boost::lexical_cast performance to be extremely slow. Wanted to find out ways to speed up the code. Using /O2 optimizati

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 11:03

    Unfortunately I don't have enough rep yet to comment...

    lexical_cast is not primarily slow because it's generic (template lookups happen at compile-time, so virtual function calls or other lookups/dereferences aren't necessary). lexical_cast is, in my opinion, slow, because it builds on C++ iostreams, which are primarily intended for streaming operations and not single conversions, and because lexical_cast must check for and convert iostream error signals. Thus:

    • a stream object has to be created and destroyed
    • in the string output case above, note that C++ compilers have a hard time avoiding buffer copies (an alternative is to format directly to the output buffer, like sprintf does, though sprintf won't safely handle buffer overruns)
    • lexical_cast has to check for stringstream errors (ss.fail()) in order to throw exceptions on conversion failures

    lexical_cast is nice because (IMO) exceptions allow trapping all errors without extra effort and because it has a uniform prototype. I don't personally see why either of these properties necessitate slow operation (when no conversion errors occur), though I don't know of such C++ functions which are fast (possibly Spirit or boost::xpressive?).

    Edit: I just found a message mentioning the use of BOOST_LEXICAL_CAST_ASSUME_C_LOCALE to enable an "itoa" optimisation: http://old.nabble.com/lexical_cast-optimization-td20817583.html. There's also a linked article with a bit more detail.

提交回复
热议问题