Like World

Like's blog

LevelDB——Arena分析

Arena可以单次申请内存,但不能单次释放内存。只有当Arena析构时,才会释放所有申请的内存。另外,Arena允许浪费内存,所以整个Arena的实现就很简洁。

分配bytes大小的空间
1
2
3
4
5
6
7
8
9
10
inline char* Arena::Allocate(size_t bytes) {
  assert(bytes > 0);
  if (bytes <= alloc_bytes_remaining_) {  //如果有足够的剩余内存,就直接分配
    char* result = alloc_ptr_;
    alloc_ptr_ += bytes;
    alloc_bytes_remaining_ -= bytes;
    return result;
  }
  return AllocateFallback(bytes);  //否则就从新分配的一块内存里分配
}
分配bytes大小的空间,返回的地址是内存对齐的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char* Arena::AllocateAligned(size_t bytes) {
  const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8; //最小8字节对齐
  assert((align & (align-1)) == 0);   // Pointer size should be a power of 2
  size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align-1); //当前指针超出对齐边界的字节数
  size_t slop = (current_mod == 0 ? 0 : align - current_mod); //需要调整的字节数
  size_t needed = bytes + slop;
  char* result;
  if (needed <= alloc_bytes_remaining_) { //有足够的剩余内存,就直接分配
    result = alloc_ptr_ + slop;
    alloc_ptr_ += needed;
    alloc_bytes_remaining_ -= needed;
  } else {
    // AllocateFallback always returned aligned memory
    result = AllocateFallback(bytes);  //否则就从新分配的一块内存里分配
  }
  assert((reinterpret_cast<uintptr_t>(result) & (align-1)) == 0);
  return result;
}
根据情况申请大块内存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static const int kBlockSize = 4096;

char* Arena::AllocateFallback(size_t bytes) {
  if (bytes > kBlockSize / 4) {  //申请大内存,就直接申请一块
    char* result = AllocateNewBlock(bytes);
    return result;
  }

  //前面剩余的内存就浪费掉了
  alloc_ptr_ = AllocateNewBlock(kBlockSize);
  alloc_bytes_remaining_ = kBlockSize;

  char* result = alloc_ptr_;
  alloc_ptr_ += bytes;
  alloc_bytes_remaining_ -= bytes;
  return result;
}
一次性分配block_bytes大小的空间
1
2
3
4
5
6
char* Arena::AllocateNewBlock(size_t block_bytes) {
  char* result = new char[block_bytes];
  blocks_memory_ += block_bytes;
  blocks_.push_back(result);
  return result;
}