Very poor boost::lexical_cast performance

后端 未结 9 997
别那么骄傲
别那么骄傲 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:20

    You could specialize lexical_cast for int and double types. Use strtod and strtol in your's specializations.

    namespace boost {
    template<>
    inline int lexical_cast(const std::string& arg)
    {
        char* stop;
        int res = strtol( arg.c_str(), &stop, 10 );
        if ( *stop != 0 ) throw_exception(bad_lexical_cast(typeid(int), typeid(std::string)));
        return res;
    }
    template<>
    inline std::string lexical_cast(const int& arg)
    {
        char buffer[65]; // large enough for arg < 2^200
        ltoa( arg, buffer, 10 );
        return std::string( buffer ); // RVO will take place here
    }
    }//namespace boost
    
    int main(int argc, char* argv[])
    {
        std::string str = "22"; // SOME STRING
        int int_str = boost::lexical_cast( str );
        std::string str2 = boost::lexical_cast( str_int );
    
        return 0;
    }
    

    This variant will be faster than using default implementation, because in default implementation there is construction of heavy stream objects. And it is should be little faster than printf, because printf should parse format string.

提交回复
热议问题