custom-allocators
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCustom Allocators
自定义 Allocator
Purpose
目的
Guide agents through memory allocator design and tuning: pool/slab/arena/buddy taxonomy, jemalloc internals and , mimalloc design, tcmalloc thread-caching, writing a simple pool allocator in C, Rust trait, fragmentation metrics, and benchmarking.
MALLOC_CONFGlobalAlloc指导 Agent 进行内存分配器设计与调优:了解 pool/slab/arena/buddy 分类体系、jemalloc 内部机制与 、mimalloc 设计、tcmalloc 线程缓存、编写简单的 C pool allocator、Rust trait、内存碎片指标以及性能基准测试。
MALLOC_CONFGlobalAllocWhen to Use
适用场景
- Replacing malloc for latency-sensitive or embedded workloads
- Tuning jemalloc/mimalloc for server heap behavior
- Implementing arena allocation for request-scoped or frame-based lifetimes
- Writing a Rust custom global allocator for or performance
no_std - Diagnosing heap fragmentation (internal vs external)
- Benchmarking allocator throughput and latency
- 为延迟敏感型或嵌入式工作负载替换 malloc
- 针对服务端堆行为调优 jemalloc/mimalloc
- 为请求作用域或基于帧的生命周期实现 arena 分配
- 为 或高性能场景编写 Rust 自定义全局分配器
no_std - 诊断堆内存碎片(内部碎片与外部碎片)
- 对 allocator 的吞吐量和延迟进行基准测试
Workflow
工作流
1. Allocator taxonomy
1. Allocator 分类体系
Allocator types
├── Pool/fixed-size — O(1) alloc/free, fixed block sizes
├── Slab — kernel-style, cache-friendly size classes
├── Arena/bump — fast alloc, bulk free (reset arena)
├── Buddy — power-of-two blocks, low fragmentation for large allocs
└── General (malloc) — jemalloc, mimalloc, tcmallocAllocator types
├── Pool/fixed-size — O(1) alloc/free, fixed block sizes
├── Slab — kernel-style, cache-friendly size classes
├── Arena/bump — fast alloc, bulk free (reset arena)
├── Buddy — power-of-two blocks, low fragmentation for large allocs
└── General (malloc) — jemalloc, mimalloc, tcmalloc2. Simple pool allocator in C
2. C 语言中的简单 pool allocator
c
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
typedef struct pool_block {
struct pool_block *next;
} pool_block_t;
typedef struct {
void *memory;
size_t block_size;
size_t num_blocks;
pool_block_t *free_list;
} pool_t;
int pool_init(pool_t *p, size_t block_size, size_t num_blocks) {
p->block_size = block_size < sizeof(pool_block_t) ?
sizeof(pool_block_t) : block_size;
p->num_blocks = num_blocks;
p->memory = aligned_alloc(64, p->block_size * num_blocks);
if (!p->memory) return -1;
p->free_list = NULL;
for (size_t i = 0; i < num_blocks; i++) {
pool_block_t *blk = (pool_block_t *)((char *)p->memory + i * p->block_size);
blk->next = p->free_list;
p->free_list = blk;
}
return 0;
}
void *pool_alloc(pool_t *p) {
if (!p->free_list) return NULL;
pool_block_t *blk = p->free_list;
p->free_list = blk->next;
return blk;
}
void pool_free(pool_t *p, void *ptr) {
pool_block_t *blk = (pool_block_t *)ptr;
blk->next = p->free_list;
p->free_list = blk;
}c
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
typedef struct pool_block {
struct pool_block *next;
} pool_block_t;
typedef struct {
void *memory;
size_t block_size;
size_t num_blocks;
pool_block_t *free_list;
} pool_t;
int pool_init(pool_t *p, size_t block_size, size_t num_blocks) {
p->block_size = block_size < sizeof(pool_block_t) ?
sizeof(pool_block_t) : block_size;
p->num_blocks = num_blocks;
p->memory = aligned_alloc(64, p->block_size * num_blocks);
if (!p->memory) return -1;
p->free_list = NULL;
for (size_t i = 0; i < num_blocks; i++) {
pool_block_t *blk = (pool_block_t *)((char *)p->memory + i * p->block_size);
blk->next = p->free_list;
p->free_list = blk;
}
return 0;
}
void *pool_alloc(pool_t *p) {
if (!p->free_list) return NULL;
pool_block_t *blk = p->free_list;
p->free_list = blk->next;
return blk;
}
void pool_free(pool_t *p, void *ptr) {
pool_block_t *blk = (pool_block_t *)ptr;
blk->next = p->free_list;
p->free_list = blk;
}3. Arena allocator
3. Arena allocator
c
typedef struct {
char *base;
size_t capacity;
size_t offset;
} arena_t;
void *arena_alloc(arena_t *a, size_t size, size_t align) {
uintptr_t cur = (uintptr_t)(a->base + a->offset);
uintptr_t aligned = (cur + align - 1) & ~(align - 1);
size_t padding = aligned - cur;
if (a->offset + padding + size > a->capacity)
return NULL;
a->offset += padding + size;
return (void *)aligned;
}
void arena_reset(arena_t *a) { a->offset = 0; }Use per-request arenas in servers — reset after response, no per-object free.
c
typedef struct {
char *base;
size_t capacity;
size_t offset;
} arena_t;
void *arena_alloc(arena_t *a, size_t size, size_t align) {
uintptr_t cur = (uintptr_t)(a->base + a->offset);
uintptr_t aligned = (cur + align - 1) & ~(align - 1);
size_t padding = aligned - cur;
if (a->offset + padding + size > a->capacity)
return NULL;
a->offset += padding + size;
return (void *)aligned;
}
void arena_reset(arena_t *a) { a->offset = 0; }在服务端中使用 per-request arena——响应完成后重置,无需逐对象 free。
4. jemalloc tuning
4. jemalloc 调优
bash
undefinedbash
undefinedUse jemalloc as system allocator
Use jemalloc as system allocator
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 ./myapp
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 ./myapp
Runtime tuning
Runtime tuning
export MALLOC_CONF="background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000"
export MALLOC_CONF="background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000"
Profiling build
Profiling build
./configure --enable-prof
./configure --enable-prof
export MALLOC_CONF="prof:true,prof_active:true,lg_prof_sample:19"
jemalloc concepts:
- **Size classes** — rounded allocation sizes
- **tcache** — per-thread cache for hot sizes
- **arenas** — reduce contention across threads
```bashexport MALLOC_CONF="prof:true,prof_active:true,lg_prof_sample:19"
jemalloc 核心概念:
- **Size class**——取整后的分配大小
- **tcache**——缓存常用大小的每线程缓存
- **arenas**——减少线程之间的争用
```bashStatistics
Statistics
export MALLOC_CONF="stats_print:true"
export MALLOC_CONF="stats_print:true"
prints on exit, or:
prints on exit, or:
mallctl("epoch", ...); mallctl("stats.allocated", ...);
undefinedmallctl("epoch", ...); mallctl("stats.allocated", ...);
undefined5. mimalloc
5. mimalloc
bash
undefinedbash
undefinedUse mimalloc
Use mimalloc
LD_PRELOAD=/usr/lib/libmimalloc.so ./myapp
LD_PRELOAD=/usr/lib/libmimalloc.so ./myapp
Environment options
Environment options
export MIMALLOC_SHOW_STATS=1
export MIMALLOC_PAGE_RESET=1
mimalloc hierarchy: segment → page → block. Generally lower metadata overhead than jemalloc.
```bashexport MIMALLOC_SHOW_STATS=1
export MIMALLOC_PAGE_RESET=1
mimalloc 层级结构:segment → page → block。通常其元数据开销低于 jemalloc。
```bashStatistics at exit
Statistics at exit
MIMALLOC_SHOW_STATS=1 ./myapp
undefinedMIMALLOC_SHOW_STATS=1 ./myapp
undefined6. tcmalloc thread-caching
6. tcmalloc 线程缓存
bash
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4 ./myappbash
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4 ./myappEnvironment
Environment
export TCMALLOC_SAMPLE_PARAMETER=524288 # sampling profiler
Per-thread caches for small objects; central heap for larger allocations.export TCMALLOC_SAMPLE_PARAMETER=524288 # sampling profiler
小型对象使用每线程缓存;较大的分配使用中央堆。7. Rust GlobalAlloc
7. Rust GlobalAlloc
rust
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct TrackingAllocator;
static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for TrackingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = System.alloc(layout);
if !ptr.is_null() {
ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed);
}
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout);
ALLOCATED.fetch_sub(layout.size(), Ordering::Relaxed);
}
}
#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator;For with crate, implement without .
#![no_std]allocGlobalAllocSystemrust
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct TrackingAllocator;
static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for TrackingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = System.alloc(layout);
if !ptr.is_null() {
ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed);
}
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout);
ALLOCATED.fetch_sub(layout.size(), Ordering::Relaxed);
}
}
#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator;对于使用 crate 的 ,应在不依赖 的情况下实现 。
alloc#![no_std]SystemGlobalAlloc8. Fragmentation metrics
8. 内存碎片指标
| Type | Definition | Detection |
|---|---|---|
| Internal | Allocated block larger than requested | Allocator stats; size class rounding |
| External | Free memory not usable for request | |
bash
undefined| 类型 | 定义 | 检测方式 |
|---|---|---|
| 内部碎片 | 分配的块大于请求大小 | Allocator 统计;size class 取整 |
| 外部碎片 | 空闲内存无法用于满足请求 | |
bash
undefinedglibc malloc_info
glibc malloc_info
malloc_info(0, stdout);
malloc_info(0, stdout);
jemalloc
jemalloc
jeprof --show_bytes ./myapp jeprof.heap
undefinedjeprof --show_bytes ./myapp jeprof.heap
undefined9. Benchmarking
9. 基准测试
bash
undefinedbash
undefinedmimalloc bench (if built from source)
mimalloc bench (if built from source)
cd mimalloc && mkdir build && cd build
cmake .. && make
./mimalloc-bench
cd mimalloc && mkdir build && cd build
cmake .. && make
./mimalloc-bench
Custom microbenchmark pattern
Custom microbenchmark pattern
perf stat -e cycles,instructions ./allocator_bench --threads 8 --size 64
Compare: single-thread alloc/free, multi-thread contention, mixed size distribution.perf stat -e cycles,instructions ./allocator_bench --threads 8 --size 64
比较项:单线程 alloc/free、多线程争用、混合大小分布。Common Problems
常见问题
| Symptom | Cause | Fix |
|---|---|---|
| Pool alloc returns NULL | Free list exhausted | Increase pool size; leak check |
| jemalloc RSS won't drop | Dirty page decay slow | Lower |
| Arena OOM | No reset between phases | |
| Rust allocator UB | Wrong Layout in dealloc | Store size/align with allocation |
| Worse perf with mimalloc | Wrong workload fit | Benchmark; try jemalloc |
| High external fragmentation | Long-lived mixed sizes | Segregate by lifetime; pools |
| 症状 | 原因 | 修复方法 |
|---|---|---|
| Pool alloc 返回 NULL | 空闲链表耗尽 | 增大 pool 大小;检查泄漏 |
| jemalloc 的 RSS 不下降 | 脏页衰减过慢 | 降低 |
| Arena OOM | 阶段之间未重置 | 使用 |
| Rust allocator 出现 UB | dealloc 时 Layout 错误 | 将 size/align 与分配信息一并存储 |
| 使用 mimalloc 后性能反而更差 | 工作负载适配错误 | 进行基准测试;尝试 jemalloc |
| 外部碎片严重 | 长期存在混合大小的分配 | 按生命周期隔离;使用 pool |
Related Skills
相关 Skill
- — NUMA-aware allocation
skills/allocators/numa-programming - — custom allocators in embedded Rust
skills/rust/rust-no-std - — allocation hotspot profiling
skills/profilers/heaptrack - — heap leak detection
skills/profilers/valgrind - — allocator alignment and false sharing
skills/low-level-programming/cpu-cache-opt - — SLUB/buddy kernel allocators
skills/kernel/kernel-internals
- ——NUMA 感知的内存分配
skills/allocators/numa-programming - ——嵌入式 Rust 中的自定义 allocator
skills/rust/rust-no-std - ——内存分配热点分析
skills/profilers/heaptrack - ——堆内存泄漏检测
skills/profilers/valgrind - ——allocator 对齐与 false sharing
skills/low-level-programming/cpu-cache-opt - ——SLUB/buddy 内核 allocator
skills/kernel/kernel-internals