Efficiency of C-String vs C++Strings

前端 未结 8 693
忘掉有多难
忘掉有多难 2020-12-28 14:20

C++ Primer says

For most applications, in addition to being safer, it is also more efficient to use library strings rather then C-style strings

8条回答
  •  梦谈多话
    2020-12-28 14:40

    Well, an obvious and simple thing how they could be practically more efficient (regarding runtime) is, that they store the string's length along with the data (or at least their size method has to be O(1), which says practically the same).

    So whenever you would need to find the NUL character in a C string (and thus walk the whole string once) you can just get the size in constant time. And this happens quite a lot, e.g. when copying or concatenating strings and thus allocating a new one beforehand, whose size you need to know.

    But I don't know if this is what the author meant or if it makes a huge difference in practice, but it still is a valid point.

提交回复
热议问题