Benefits of vector over string?

后端 未结 7 1487
自闭症患者
自闭症患者 2020-12-14 09:52

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

Are there any benefits to using std::vector instead of std::str

相关标签:
7条回答
  • 2020-12-14 10:19

    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.

    0 讨论(0)
提交回复
热议问题