Performance stringbuf vs string

When we need to work with string manipulations, are there any significant performance differences between std :: string and std :: stringbuf, and if so, why.

More generally, when is it useful to use std :: stringbuf via std :: string?

+6
source share
3 answers

A std::stringbuf uses an internal string to buffer data, so it is probably a bit slower. I do not think that the difference would be significant, because it is basically just delegation. Of course, you will have to run some performance tests.

std::stringbuf is useful when you want an IO stream to use a string as a buffer (for example, std::stringstream , which uses std::stringbuf ).

+6
source

First of all, std::stringbuf does not necessarily (or even usually) use std::string for its internal storage. For example, the standard describes initialization from std::string as follows:

Creates an object of class basic_stringbuf ... Then copies the contents of str to the basic sequence of characters basic_stringbuf [...]

Pay attention to the wording: "sequence of characters" - at least for me it seems rather careful not to say (or even imply) that the contents should be stored in a real line.

The past, I think, efficiency is probably a red herring. Both of them are rather thin wrappers for managing dynamically allocated buffers of some characteristic sequence. There is a big difference in capabilities (for example, string has many search and insert / delete operations in the middle of the string, which are completely absent in stringbuf ). Given its purpose, it may make sense to implement stringbuf on top of something like std::deque in order to optimize the (regular) insert / delete path at the ends, but for most purposes this may not be relevant.

If I did this, I would be most concerned about the fact that stringbuf is probably being tested with stringstream , so if I used it other than stringstream , I might run into problems even if I follow what the standard says he should support.

+3
source

std::stringbuf extends the std::string container for reading and writing to std::string .

Typically, there is no significant performance difference between std::string and std::stringbuf .

Because std::streambuf <- std::stringbuf , because:

 typedef basic_stringbuf<char> stringbuf; typedef basic_string<char> string; 

Read this for more details.

0
source

Source: https://habr.com/ru/post/914109/


All Articles