Why FBString Beats std::string: Three‑Tier Storage and Jemalloc Magic
This article explains how FBString improves performance over std::string by using a three‑tier storage strategy, tight integration with jemalloc, and specialized techniques like SSO, eager copy, and copy‑on‑write, detailing its core implementation and key functions.
FBString Overview
fbstring is a drop‑in replacement for std::string . Its main benefit is significantly increased performance on virtually all important primitives, achieved through a three‑tier storage strategy and cooperation with the memory allocator, especially jemalloc.
Storage Strategies
SSO (Small‑String Optimization) : Uses a stack‑based buffer to store up to 23 characters directly in the class’s array member.
Eager Copy : Stores strings up to 254 characters on the heap allocated by malloc .
Copy‑On‑Write (COW) : For strings longer than 254 characters, introduces reference counting to avoid unnecessary copies.
Core Implementation
fbstring_core is the implementation core providing all operation interfaces and realizing the three‑tier storage and memory allocation strategy.
The class can be in one of three states— small , medium , or large —and transitions between them during construction, assignment, expansion, or shrinkage. The category() method returns the current state.
Data members are stored in a union where small_ handles the small state and MediumLarge handles medium and large states. In the small state, the last byte stores maxSmallSize - currentSize .
RefCounted supports COW in the large state. It uses std::atomic for the reference count, and data_ points to the counted entity. The function fromData(Char* p) obtains the corresponding RefCounted pointer from the entity pointer.
Constructor
Construction follows the three‑state strategy, initializing the appropriate storage based on the string length.
Move Constructor
Swap Function
void swap(fbstring_core & rhs) { auto const t = ml_; ml_ = rhs.ml_; rhs.ml_ = t; }
Related Links
http://en.cppreference.com/w/cpp/atomic/atomic
http://en.cppreference.com/w/cpp/language/move_constructor
360 Zhihui Cloud Developer
360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.