Very poor boost::lexical_cast performance

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

    What lexical cast is doing in your code can be simplified to this:

    string Cast( int i ) {
        ostringstream os;
        os << i;
        return os.str();
    }
    

    There is unfortunately a lot going on every time you call Cast():

    • a string stream is created possibly allocating memory
    • operator << for integer i is called
    • the result is stored in the stream, possibly allocating memory
    • a string copy is taken from the stream
    • a copy of the string is (possibly) created to be returned.
    • memory is deallocated

    Thn in your own code:

     s = Cast( i );
    

    the assignment involves further allocations and deallocations are performed. You may be able to reduce this slightly by using:

    string s = Cast( i );
    

    instead.

    However, if performance is really importanrt to you, you should considerv using a different mechanism. You could write your own version of Cast() which (for example) creates a static stringstream. Such a version would not be thread safe, but that might not matter for your specific needs.

    To summarise, lexical_cast is a convenient and useful feature, but such convenience comes (as it always must) with trade-offs in other areas.

提交回复
热议问题