简介
内存切片分配器使用了复杂的分层设计,灵感来自Bonwick的slab内存分配器,它提供了一种节省空间和多处理可扩展的方式来分配相等大小的内存,避免了过多的内存浪费,还兼顾了可伸缩性和性能问题。
内存切片分配器使用posix_memaligin()来优化许多相同大小的块内存分配,并根据线程可利用空间表(free list)来快速分配指定结构大小的内存。在内存释放之后,额外的缓存逻辑还该内存保留一段时间。
一般来说,频繁申请释放的小块内存,建议使用内存切片分配器。
数据结构
无特殊数据结构
函数列表
gpointer g_slice_alloc ()
gpointer g_slice_alloc0 ()
gpointer g_slice_copy ()
void g_slice_free1 ()
void g_slice_free_chain_with_offset ()
#define g_slice_new()
#define g_slice_new0()
#define g_slice_dup()
#define g_slice_free()
#define g_slice_free_chain()
函数功能分类
申请
// g_slice_new是对g_slice_alloc的封装,使用更方便。结尾带0的函数,申请到内存后会将内存初始化为0
gpointer g_slice_alloc ()
gpointer g_slice_alloc0 ()
#define g_slice_new()
#define g_slice_new0()
释放
// 使用g_slice_alloc和g_slice_alloc0申请的内存由本函数释放
void g_slice_free1 ()
// 对g_slice_free1的封装,使用更便捷
#define g_slice_free()
// 释放类似GList那种链式数据结构的内存,只要是next方式链接的数据结构都可以
#define g_slice_free_chain()
void g_slice_free_chain_with_offset ()
拷贝
// 将一段内存拷贝到其他地方,g_slice_dup是对g_slice_copy的封装
gpointer g_slice_copy ()
#define g_slice_dup()
函数功能说明及综合演示
内存申请
申请10000个数组指针,每个数组的长度为50,数组元素的值为整数,使用内存切片分配器分配内存。
示例代码如下:
源码见glib_examples\glib_mem_slices\glib_mem_slices_basic
#include <glib.h>
gint main(gint argc, gchar **argv)
{
gchar *mem[10000];
gint i,j;
// Allocate 10000 blocks.
for (i = 0; i < 10000; i++) {
mem[i] = g_slice_alloc (50);
// Fill in the memory with some junk.
for (j = 0; j < 50; j++) {
mem[i][j] = i * j;
}
}
// Now free all of the blocks.
for (i = 0; i < 10000; i++) {
g_slice_free1 (50, mem[i]);
}
return 0;
}
自定义数据结构内存申请
自定义一个数据结构,使用内存切片分配器为其分配内存。
示例代码如下:
源码见glib_examples\glib_mem_slices\glib_mem_slices_struct
#include <glib.h>
typedef struct _GRealArray
{
guint8 *data;
guint len;
guint alloc;
guint elt_size;
guint zero_terminated : 1;
guint clear : 1;
gint ref_count;
GDestroyNotify clear_func;
}GRealArray;
gint main(gint argc, gchar **argv)
{
GRealArray *array;
guint zero_terminated = 0;
guint clear = 0;
guint elt_size = 100;
// Allocate one block, using the g_slice_new() macro.
array = g_slice_new (GRealArray);
// We can now use array just like a normal pointer to a structure.
array->data = NULL;
array->len = 0;
array->alloc = 0;
array->zero_terminated = (zero_terminated ? 1 : 0);
array->clear = (clear ? 1 : 0);
array->elt_size = elt_size;
// We can free the block, so it can be reused.
g_slice_free (GRealArray, array);
return 0;
}