💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
通常在Golang中,当我们谈论内存管理的时候,主要是指堆内存的管理,因为栈的内存管理不需要程序去操心。 [![](https://github.com/KeKe-Li/data-structures-questions/raw/master/src/images/130.jpg)](https://github.com/KeKe-Li/data-structures-questions/blob/master/src/images/130.jpg) 堆内存管理中主要是三部分, 1.分配内存块,2.回收内存块, 3.组织内存块。 [![](https://github.com/KeKe-Li/data-structures-questions/raw/master/src/images/131.jpg)](https://github.com/KeKe-Li/data-structures-questions/blob/master/src/images/131.jpg) 一个内存块包含了3类信息,如下图所示,元数据、用户数据和对齐字段,内存对齐是为了提高访问效率。下图申请5Byte内存的时候,就需要进行内存对齐。 [![](https://github.com/KeKe-Li/data-structures-questions/raw/master/src/images/132.jpg)](https://github.com/KeKe-Li/data-structures-questions/blob/master/src/images/132.jpg) 释放内存实质是把使用的内存块从链表中取出来,然后标记为未使用,当分配内存块的时候,可以从未使用内存块中有先查找大小相近的内存块,如果找不到,再从未分配的内存中分配内存。 上面这个简单的设计中还没考虑内存碎片的问题,因为随着内存不断的申请和释放,内存上会存在大量的碎片,降低内存的使用率。为了解决内存碎片,可以将2个连续的未使用的内存块合并,减少碎片。 想要深入了解可以看下这个文章,《Writing a Memory Allocator》.