C++ equivalent of StringBuffer/StringBuilder?

前端 未结 10 913
说谎
说谎 2020-11-29 15:51

Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#\'s StringBuilder or Java\'s StringBuffer?

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 16:23

    I wanted to add something new because of the following:

    At a first attemp I failed to beat

    std::ostringstream 's operator<<

    efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.

    Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.

    The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):

    • 1 byte header (2 bits to tell if following data is :moved string, string or byte[])
    • 6 bits to tell lenght of byte[]

    for byte [ ]

    • I store directly bytes of short strings (for sequential memory access)

    for moved strings (strings appended with std::move)

    • The pointer to a std::string object (we have ownership)
    • set a flag in the class if there are unused reserved bytes there

    for strings

    • The pointer to a std::string object (no ownership)

    There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)

    This was finally slightly faster than std::ostringstream but it has few downsides:

    • I assumed fixed lenght char types (so 1,2 or 4 bytes, not good for UTF8), I'm not saying it will not work for UTF8, Just I don't checked it for laziness.
    • I used bad coding practise (opaque buffer, easy to make it not portable, I believe mine is portable by the way)
    • Lacks all features of ostringstream
    • If some referenced string is deleted before mergin all the strings: undefined behaviour.

    conclusion? use std::ostringstream

    It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.

提交回复
热议问题