What are the problems of a zero-terminated string that length-prefixed strings overcome?

后端 未结 6 1834
滥情空心
滥情空心 2021-02-06 21:57

What are the problems of a zero-terminated string that length-prefixed strings overcome?

I was reading the book Write Great Code vol. 1 and I had that question in mind.<

6条回答
  •  一个人的身影
    2021-02-06 22:23

    One problem is that with zero-terminated strings you have to keep finding the end of the string repeatedly. The classic example where this is inefficient is concatenating into a buffer:

    char buf[1024] = "first";
    strcat(buf, "second");
    strcat(buf, "third");
    strcat(buf, "fourth");
    

    On every call to strcat the program has to start from the beginning of the string and find the terminator to know where to start appending. This means the function spends more and more time finding the place to append as the string grows longer.

    With a length-prefixed string the equivalent of the strcat function would know where the end is immediately, and would just update the length after appending to it.

    There are pros and cons to each way of representing strings and whether they cause problems for you depend on what you are doing with strings, and which operations need to be efficient. The problem described above can be overcome by manually keeping track of the end of the string as it grows, so by changing the code you can avoid the performance cost.

提交回复
热议问题