memcached的内存存储

Slab Allocation机制

memcached默认情况下采用了名为Slab Allocator的机制来分配、管理内存。 在该机制出现以前,内存的分配是通过对所有记录简单地进行malloc和free来进行的。 但是,这种方式会导致内存碎片,加重操作系统内存管理器的负担,最坏的情况下, 会导致操作系统比memcached进程本身还慢。Slab Allocator就是为解决该问题而诞生的。

slab allocator的原理

the primary goal of the slabs subsystem in memcached was to eliminate memory fragmentation issues totally by using fixed-size memory chunks coming from a few predetermined size classes.

Slab Allocator的基本原理是按照预先规定的大小,将分配的内存分割成特定长度的块, 以完全解决内存碎片问题。

Slab Allocation的原理相当简单。 将分配的内存分割成各种尺寸的块(chunk), 并把尺寸相同的块分成组(chunk的集合),如下图,而且,slab allocator可以重复使用已分配的内存。 也就是说,分配到的内存不会释放,而是重复利用。

系统分配给Slab的内存空间称为page,默认是1MB。分配给Slab之后根据slab的大小切分成chunk,chunk用于缓存记录,特定大小的chunk组称为slab class。

memcached根据收到的数据的大小,选择最适合数据大小的slab,如下图。memcached中保存着slab内空闲chunk的列表,根据该列表选择chunk, 然后将数据缓存于其中。

Slab Allocator的缺点

从slab的原理就知道,内存空间还是不能100%的得到利用,比如对于一个100 bytes的数据,slab会选择最合适的chunk大小为112bytes,这回造成12bytes的内存空间浪费。

对于这个缺点文档里有一个说明:

The most efficient way to reduce the waste is to use a list of size classes that closely matches (if that’s at all possible) common sizes of objects that the clients of this particular installation of memcached are likely to store.

就是说,如果预先知道客户端发送的数据的大小,或者仅缓存大小相同的数据, 或者只要使用适合数据大小的组的列表,就可以减少浪费。当然实际的情况是很难做到以上几点,所以也只能通过参数调整来达到尽量少的浪费内存。


你可能感兴趣的:(memcached的内存存储)