Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Benefits of vector<char> over string?

This question is related to, but not quite the same as, this question.

Are there any benefits to using std::vector<char> instead of std::string to hold arbitrary binary data, aside from readability-related issues?

i.e. Are there any tasks which are easier/more efficient/better to perform with a vector compared to a string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Aside from readability (which should not be underestimated) I can think of a couple of minor performance/memory issues with using std::string over std::vector:

  • Some modern std::string implementations use the small string optimization. If you are storing data that's larger than the string's internal buffer, it becomes a pessimization, reducing the efficiency of copying, moving, and swap1 and increasing the sizeof() for no benefit.

  • An efficient std::string implementation will always allocate at least 1 more byte than the current size for storing a terminating null (not doing so requires extra logic in operator[] to cope with str[size()]).

I should stress that both of these issues are very minor; the performance cost of them will more than likely be lost in the background noise. But you did ask.


1Those operations require branching on size() if the small string optimization is being used, whereas they don't in a good std::vector implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...