by vlovich123 · 3y ago · 0 comments
The other advantage is that there’s nothing involved in porting C strings between 8, 16, 32, and 64 bit machines.
Of course, most modern languages will store the length separately (using small string optimization) AND offer a way to convert to a C string (for OS interop).
There’s an argument that taking a substring off a C string a) can be done without allocating a copy b) can be done with pure pointer manipulation. In practice though I’m not sure how critical that case is.
Rust supports the same features by storing the length of the string with the pointer. Same thing with other references to dynamically sized memory (slices).
Variable length encodings like varint [1] allows to use 1 byte for small integers and more for large. Zero terminated string will use less memory for large strings, but the difference between 1 (\0) and 3 bytes (varint length) for a 64k string is negligible.
This might work fine in a bank mainframe, but is prohibitively expensive in the minicomputers back in the days.
C is written for Unix. Unix is written with minicomputers in mind. Thus C is somewhat influenced by minicomputers and has to work on their setback in the good ol' days.
You have to think in the historic context.
It causes strictly less indirect access if you store it as part of the string struct, as C++, Go, or Rust do.
It’s more clear today but that’s because we’ve had 20 years of data of various experiments and ideas like small string optimizations on modern architectures that didn’t exist 40+ years ago.
You can optimize the common case of string data following the header by encoding the fact in a bit of the length field.
E.g. if the length is odd (LSB = 1) then the next word contains the pointer to the string body, otherwise the string body follows the length field. Archs that lack tagged arithmetic would require a shift but at least that skips a memory read for the string data indirection.