- 跟上一篇隔得時間有點久啊,得加強自律性了......
- FBString這貨基本上用到了所有常見的實現String的方法,有一定的學習和參考價值
- 大家猜猜這個FBString的作者是誰,答案在篇尾
FBString簡介
fbstring is a drop-in replacement for std::string. The main benefit of fbstring is significantly increased performance on virtually all important primitives. This is achieved by using a three-tiered storage strategy and by cooperating with the memory allocator. In particular, fbstring is designed to detect use of jemalloc and cooperate with it to achieve significant improvements in speed and memory usage.
簡單來說,使用了三層存儲策略+內存分配策略+大小端支持,特別是配合使用 jemalloc, 減少磁盤碎片,加快并發下的分配速度和性能。
存儲策略
- SSO技術,使用棧上緩沖區,存儲字符不超過23個,存儲在類的數組類型的成員變量中;
- Eager Copy技術,存儲字符不超過254個,總是存儲在malloc分配的堆上內存空間;
- Copy-On-Write技術,存儲字符超過254, 使用COW技術,引入引用計數,避免不必要的copy操作。
核心實現
fbstring_core
- 是FBString的實現核心,提供了全部的操作接口,實現了三層存儲策略+內存分配策略+大小端支持;
- 用戶可根據需要實現自己的fbstring_core_model(即fbstring_core的mockup接口定義)接口,即實現了自己的String類;
- 可以用狀態機的思路來理解fbstring_core, 按存儲策略的不同其當前可能處于三種不同的狀態:small, medium, large, 當構造,賦值,擴容,收縮等操作發生時,會在這三種狀態間轉換,即其存儲策略也會相應主調整,大部分函數都按這個思路來閱讀吧;
- category() 可獲取當前的狀態:small, medium, large,下面我們會經常提到這三種狀態;
- 數據成員
struct MediumLarge {
Char * data_;
size_t size_;
size_t capacity_;
size_t capacity() const {
return kIsLittleEndian
? capacity_ & capacityExtractMask
: capacity_ >> 2;
}
void setCapacity(size_t cap, Category cat) {
capacity_ = kIsLittleEndian
? cap | static_cast<category_type>(cat)
: (cap << 2) | static_cast<category_type>(cat);
}
};
union {
Char small_[sizeof(MediumLarge) / sizeof(Char)];
MediumLarge ml_;
};
使用了union,其中small_用于small狀態時的字符串存儲,MediumLarge用于medium和large狀態時的字符串存儲;
使用small_時,其最后一格存儲 maxSmallSize - 當前字符串實現大小
這個看起來還是一目了然,很清楚的。
- RefCounted
struct RefCounted {
std::atomic<size_t> refCount_;
Char data_[1];
static RefCounted * fromData(Char * p) {
return static_cast<RefCounted*>(
static_cast<void*>(
static_cast<unsigned char*>(static_cast<void*>(p))
- sizeof(refCount_)));
}
static size_t refs(Char * p) {
return fromData(p)->refCount_.load(std::memory_order_acquire);
}
static void incrementRefs(Char * p) {
fromData(p)->refCount_.fetch_add(1, std::memory_order_acq_rel);
}
static void decrementRefs(Char * p) {
auto const dis = fromData(p);
size_t oldcnt = dis->refCount_.fetch_sub(1, std::memory_order_acq_rel);
assert(oldcnt > 0);
if (oldcnt == 1) {
free(dis);
}
}
static RefCounted * create(size_t * size) {
// Don't forget to allocate one extra Char for the terminating
// null. In this case, however, one Char is already part of the
// struct.
const size_t allocSize = goodMallocSize(
sizeof(RefCounted) + *size * sizeof(Char));
auto result = static_cast<RefCounted*>(checkedMalloc(allocSize));
result->refCount_.store(1, std::memory_order_release);
*size = (allocSize - sizeof(RefCounted)) / sizeof(Char);
return result;
}
static RefCounted * create(const Char * data, size_t * size) {
const size_t effectiveSize = *size;
auto result = create(size);
fbstring_detail::pod_copy(data, data + effectiveSize, result->data_);
return result;
}
static RefCounted * reallocate(Char *const data,
const size_t currentSize,
const size_t currentCapacity,
const size_t newCapacity) {
assert(newCapacity > 0 && newCapacity > currentSize);
auto const dis = fromData(data);
assert(dis->refCount_.load(std::memory_order_acquire) == 1);
// Don't forget to allocate one extra Char for the terminating
// null. In this case, however, one Char is already part of the
// struct.
auto result = static_cast<RefCounted*>(
smartRealloc(dis,
sizeof(RefCounted) + currentSize * sizeof(Char),
sizeof(RefCounted) + currentCapacity * sizeof(Char),
sizeof(RefCounted) + newCapacity * sizeof(Char)));
assert(result->refCount_.load(std::memory_order_acquire) == 1);
return result;
}
};
看著代碼多,其實很簡單。
在large狀態使用COW技術就需要引用計數的存在,這個RefCounted就實現了這個,利用了std::atomic作計數,data_指向需要作計數的實體。fromData(Char p)*函數從需作計數的實體指針得到其對應的RefCounted實體的指針。
構造函數
- 基本上都是按三種狀態對應的策略來構造
- Move constructor
fbstring_core(fbstring_core&& goner) noexcept {
// Take goner's guts
ml_ = goner.ml_;
// Clean goner's carcass
goner.reset();
}
交換函數
- void swap(fbstring_core & rhs)
auto const t = ml_;
ml_ = rhs.ml_;
rhs.ml_ = t;
實現簡單,用處多多
### 訪問函數
- const Char * data() const
- const Char * c_str()
- Char * mutable_data()
large狀態的,要作拷貝啦~~~COW
### 回縮函數
- void shrink(const size_t delta)
size減少delta. "得兒塔" 讓我想起了中學的數學課~~~還有我同桌
### Reserve函數
- void reserve(size_t minCapacity, bool disableSSO)
讓這個string的capacity至少有minCapacity這么大,這個函數完美詮釋了三種狀態的轉換。
## basic_fbstring
- 這個其實沒什么說的,用fbstring_core的接口把std::string的所有接口都實現了一遍。
- 最后還附贈了一個 **typedef basic_fbstring<char> fbstring** 外加一個**FOLLY_FBSTRING_HASH**
# FBString作者:[Andrei Alexandrescu](https://zh.wikipedia.org/wiki/%E5%AE%89%E5%BE%B7%E7%83%88%C2%B7%E4%BA%9E%E6%AD%B7%E5%B1%B1%E5%BE%B7%E9%9B%B7%E6%96%AF%E5%BA%AB) C++和D語言專家