r/C_Programming • • 10d ago

Tiny strings

https://napcakes.nekoweb.org/posts/tiny-strings/
33 Upvotes

13 comments sorted by

View all comments

3

u/YetAnotherRobert 10d ago

Timely. I looked this topic up just hours before seeing this. This is very close to Clang's std::string SSO. iIRC, that structure is 24 bytes (that's probably on on 32-bits, though you can probably do better than the naive "twice that"  on a 64 bitter[1]) and they can use 22 bytes for SSO. Same basic trick of storing length<<1 so that bit 0 could be a flag and the thing collapses to a std::string_view beautifully.

The point of the discussion was that, especially on modern architecture, sometimes "clever"  is a huge win over dead simple. Having most (or even merely "many") of your strings right there, not just on the same page, but probably in the same cache line that was already preferched and bursted in on the same cache line is worth a couple of (overlapping, nightly speculatable) ops in the execution pipeline. There's a LOT of real world code suffering problems like the linked game parser. We've all had to wreck an internal calling convention because we need the bottom layer to extend a string or insert something in the middle, so you have to reallocate the thing you were passed, hopefully without creating leaks.

[1]Start and end pointers are probably not more than even 20 bits apart and the pointer to any allocated buffer is probably within an exabyte or two. Sure, there are strings longer than any N you can pick, but having a compact representation of what's p robably the most common non-pod type is worth whipping out some clevers. (And test suite coverage...)