Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance stringbuf vs string

Tags:

c++

string

When we have to work with string manipulation, is there any significants performance difference between std::string and std::stringbuf, and if yes why.

More generally when it is good to use std::stringbuf over std::string ?

like image 728
Guillaume Paris Avatar asked Apr 25 '12 09:04

Guillaume Paris


2 Answers

A std::stringbuf uses a string internally to buffer data, so it is probably a bit slower. I don't think the difference would be significant though, because it basically just delegation. To be sure you'd have to run some performance-tests though.

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

like image 63
Björn Pollex Avatar answered Oct 01 '22 12:10

Björn Pollex


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

Constructs an object of class basic_stringbuf ... Then copies the content of str into the basic_stringbuf underlying character sequence [...]

Note the wording: "character sequence" -- at least to me, this seems to be quite careful to avoid saying (or even implying) that the content should be stored in an actual string.

Past that, I think efficiency is probably a red herring. Both of them are fairly thin wrappers for managing dynamically allocated buffers of some sort of character-like sequence. There's a big difference in capabilities (e.g., string has lots of searching and insertion/deletion in the middle of a string that are entirely absent from stringbuf). Given its purpose, it might make sense to implement stringbuf on top of something like a std::deque, to optimize the (usual) path of insertion/deletion at the ends, but this is likely to be insubstantial for most uses.

If I were doing it, I'd probably be most worried by the fact that stringbuf is probably only tested along with stringstream, so if I used it differently than stringstream did, I might encounter problems, even if I'm following what the standard says it should support.

like image 42
Jerry Coffin Avatar answered Oct 01 '22 11:10

Jerry Coffin