Efficiency of C-String vs C++Strings

前端 未结 8 674
忘掉有多难
忘掉有多难 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:37

    There are some cases in which a std::string might beat a char[]. For example, C-style strings typically don't have an explicit length passed around—instead, the NUL terminator implicitly defines the length.

    This means that a loop which continually strcats onto a char[] is actually performing O(n²) work, because each strcat has to process the entire string in order to determine the insertion point. In contrast, the only work that a std::string needs to perform to concatenate onto the end of a string is to copy the new characters (and possibly reallocate storage—but for the comparison to be fair, you have to know the maximum size beforehand and reserve() it).

提交回复
热议问题