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.