4 ms·
In situations when there might be a lot of _empty_ strings, the 'capacity' and 'size' can be taken out of the fixed part and bundled with the data instead. Thi
by huhtenberg 7y ago
In situations when there might be a lot of _empty_ strings, the 'capacity' and 'size' can be taken out of the fixed part and bundled with the data instead.
This will bring sizeof(string) to a size of a single pointer and will still allow for short strings of 7 chars (in 64-bit builds).
Memory allocations are usually aligned by default, so the pointers will have at least one lower bit cleared and available to be used as a mode flag.
If in doubt, allocating through aligned_alloc(2,...) will guarantee an unused bit in a pointer.
- gpderetta 7y agoYes, sometimes it is worth to optimize for size, especially if the string is actually not used in any fast path and just need to be there. I'll mention though that std::string (well, basic_string) takes an allocator parameter, so it could only enable this optimization for 'well known' allocators that provide aligned buffers.