What is CompactString and when to use it
mainA CompactString is a memory-efficient string type that implements Small String Optimization (SSO). It can store up to 24 bytes (on 64-bit architectures) or 12 bytes (on 32-bit architectures) directly on the stack. If a string exceeds this size, it is transparently stored on the heap.
Key use cases:
- As a drop-in replacement for
Stringto reduce heap allocations. - In parsing, deserializing, or applications where many small strings are present.
Key Properties:
size_of::<CompactString>() == size_of::<String>()(it won't increase your stack frame size).CloneisO(n).From<String>orFrom<Box<str>>re-uses the underlying buffer where possible.O(1)creation from&'static strusingCompactString::const_new.- Space optimized for
Option<CompactString>:size_of::<CompactString>() == size_of::<Option<CompactString>>().