Out of curiosity what's the scenario where you care about saving a few bytes per string where possible, but also don't mind pulling in the whole String class? Wouldn't it be more efficient to do everything in c-strings across the board?
For small strings, 1-15 bytes, this implementation already beats C strings. C strings, by definition, do indirection. So you need a pointer (say ~8 bytes) plus N+1 bytes for storing the actual string and '\0'. And that's discounting allocator overhead.
On the more "efficient" aspect, there's nothing efficient about C strings. The only thing that you can do painlessly is print them. Try to make a substring and realise that you can't, so you have to allocate a whole new string. Every operation requires either traversing the whole string to get its length, potentially many times over the course of a running program, or write code with loop-carried dependencies -- incredibly slow too but also error-prone.
I'm pretty sure C strings are the biggest source of bugs in C programs. If you look around, no other language does strings this way. Keeping the length is important!
How do you get around the pointer when passing the struct around?
By my accounting the minimum string (empty) would be 9 bytes if you're assuming an 8 byte pointer (Far larger than most platforms I use) and the null terminator, meaning 9 bytes of memory total.
For the struct you would need the struct (16 bytes) and the pointer to the struct (another 8 bytes).
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).
View all comments
7
u/manystripes 9d ago
Out of curiosity what's the scenario where you care about saving a few bytes per string where possible, but also don't mind pulling in the whole String class? Wouldn't it be more efficient to do everything in c-strings across the board?