Efficiency of C-String vs C++Strings

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

    The difficulty with C-style strings is that one really can't do much with them unless one knows about the data structures in which they are contained. For example, when using "strcpy", one must know that the destination buffer is writable, and has enough space to accommodate everything up to the first zero byte in the source (of course, in all too many cases, one doesn't really know that for certain...). Very few library routines provide any support for allocating space on demand, and I think all those that do work by allocating it unconditionally (so if one had a buffer with space for 1000 bytes, and one wants to copy a 900-byte string, code using those methods would have to abandon the 1000-byte buffer and then create a new 900-byte buffer, even though it might be better to simply reuse the 1000-byte buffer).

    Working with an object-oriented string type would in many cases not be as efficient as working with standard C-strings but figuring out the optimal ways to allocate and reuse things. On the other hand, code which is written to optimally allocate and reuse strings may be very brittle, and slight changes to requirements could require making lots of tricky little tweaks to the code--failing to tweak the code perfectly would likely result in bugs which may be obvious and severe, or subtle but even more severe. The most practical way to avoid brittleness in code which uses standard C strings is to design it very conservatively. Document maximum input-data sizes, truncate anything which is too big, and use big buffers for everything. Workable, but not terribly efficient.

    By contrast, if one uses the object-oriented string types, the allocation patterns they use will likely not be optimal, but will likely be better than the 'allocate everything big' approach. They thus combine much of the run-time efficiency of the hand-optimized-code approach with safety that's better than the 'allocate everything big' approach.

提交回复
热议问题