r/C_Programming • • 12d ago

Tiny strings

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

13 comments sorted by

View all comments

Show parent comment

5

u/8d8n4mbo28026ulk 12d ago edited 12d ago

You don't need a pointer to the structure, just the structure itself, so 16 bytes. In those 16 bytes, at any time, a small string of at most 15 bytes is stored, or a (size, pointer) pair to some separately allocated memory region.

So, let's take "sufficientlybig" as an example. To store this using C strings, you need an 8 byte pointer plus the 15 bytes of the string itself plus 1 for '\0', for a total of 24 bytes, 8 bytes more than with the 16-byte structure.

For the small cases, C strings would only save you more if every single string you store is 6 bytes or less (again, ignoring allocator overhead). But that comes at a tremendous cost: you lose the length. Thus, if at any point in time you want a substring, which is very common, you suddenly need to allocate a new string. And code size bloats too, because many operations on C strings require a bunch of stupid code that you otherwise wouldn't need to write (strlen() is the prime example).