Quantcast
Channel: User CPlus - Programming Language Design and Implementation Stack Exchange
Viewing all articles
Browse latest Browse all 66

Answer by CPlus for What are the advantages/disadvantages of null-terminated strings vs length-prefixed strings?

$
0
0

Short String Optimization

One way one could save having to allocate a separate buffer at a separate location is short string optimization. The idea is if the string is shorter than the size of a pointer, the data can be stored in the space of the pointer. However, this requires knowing the size of the string beforehand. An example of how this could be implemented in C would be:

typedef struct String {    size_t len;    union {        char *ptr, data[sizeof(char *)];    };} String;

And if len < sizeof(char *), access data directly, otherwise, access ptr.

A language could have string optimizations like this built-in, but of course, this is only possible if the length is known before-hand, which is not possible with null-terminated strings.


Viewing all articles
Browse latest Browse all 66

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>