Skip to content
quboliu
Go back

Repost · Bilingual

Memory Allocation in GoGo 中的内存分配

Area: Go 语言Edit page

Contents目录

Disclaimer适用范围

This blog post primarily focuses on Go 1.24 programming language running on Linux on ARM architecture. It may not cover platform-specific details for other operating systems or hardware architectures.

本文主要讨论在 ARM 架构的 Linux 上运行的 Go 1.24,其他操作系统或硬件架构可能有各自的实现细节,本文未必涉及。

The content is based on other sources and my own understanding of Go, so it might not be entirely accurate. Feel free to correct me or give suggestions in the comment section at the very bottom 😄.

文章依据参考资料和我自己对 Go 的理解写成,难免有不准确之处。欢迎在文末评论区指出问题或提出建议 😄。

Introduction引言

Memory allocation is at the heart of every programming language runtime, and Go is no exception. Efficient allocation and management of memory directly affect the performance, scalability, and responsiveness of Go applications. While Go abstracts away most of the complexity through its simple APIs (new(T), &T{} and make), understanding what happens under the hood gives us valuable insight into how the runtime achieves efficiency, and where potential bottlenecks may arise.

内存分配是每门编程语言运行时的核心,Go 也不例外。内存的分配和管理效率直接影响 Go 应用的性能、可扩展性和响应速度。new(T)、&T{} 和 make 这些简单的接口隐藏了大部分复杂性。看看它们背后发生了什么,有助于理解运行时如何做到高效,以及瓶颈可能出在哪里。

In this post, we’ll explore Go’s memory allocator in depth. We’ll look at its core components, how they interact to serve allocations of different sizes, and how stacks are managed alongside heap objects. Along the way, we’ll examine some case studies to understand the practical implications of Go’s memory allocation strategies. By the end, you should have a clearer picture of how Go abstracts memory management while offers high performance.

本文将深入 Go 的内存分配器。我们会逐一认识它的核心组件,看它们怎样配合处理不同大小的分配请求,以及运行时怎样管理堆对象和栈。文末还会通过几个实例观察这些策略在实际程序中的效果。读完后,你应该能更清楚地理解 Go 如何在提供内存管理抽象的同时保持高性能。

Before diving into how Go allocates memory, it’s essential to understand some fundamental concepts about how memory works in a typical operating system. I suggest you read the Fundamental of Virtual Memory post first. If you are already familiar with those concepts, just skip that post. Now, let’s dive into Go’s view of virtual memory.

在讨论 Go 如何分配内存之前,先要了解一般操作系统的内存机制。我建议先读《虚拟内存基础》;如果已经熟悉这些概念,可以直接往下看 Go 运行时眼中的虚拟内存。

Go’s View of Virtual MemoryGo 运行时眼中的虚拟内存

As a Go process is simply a user-space application, it follows the standard virtual memory layout described in the fundamental post. Specifically, the Stack segment of the process is the g0 stack (aka. system stack) associated with the main thread m0 of the Go runtime. Initialized (i.e. having non-zero value) global variables are stored in the Data segment, while uninitialized ones reside in the BSS segment.

Go 进程是普通的用户态应用,遵循前文介绍的标准虚拟内存布局。具体来说,进程的栈段是 Go 运行时主线程 m0 对应的 g0 栈,也叫系统栈。初值非零的全局变量放在数据段,未初始化的全局变量放在 BSS 段。

The traditional Heap segment, which is located under the program break, is not utilized by the Go runtime to allocate heap objects. Instead, Go runtime relies heavily on memory-mapped segments for allocating memory for heap objects and goroutine stacks. From now on, I’ll refer to that memory-mapped segments Go uses for dynamic allocation as the heap, which not to be confused with the traditional process heap under the program break.

传统的堆段位于 程序断点之下,Go 运行时不从这个区域分配堆对象。堆对象和 goroutine 栈主要从内存映射区域分配。下文将 Go 用于动态分配的这部分映射区域简称为“堆”,以便与程序断点之下的传统进程堆区分。

Go 运行时所见的虚拟内存布局
Virtual memory layout from Go runtime’s perspective
Go 运行时所见的虚拟内存布局

Arena and PageArena 与页

To manage this memory efficiently, Go runtime partitions these memory-mapped segments into hierarchical units, ranging from coarse-grained to fine-grained. The most coarse-grained units are known as an arenas, a fixed-size region of 64 MB. Go runtime tries to make arenas contiguous, but they are not necessarily so due to the behavior of mmap system call, which may return a different address than requested.

为了高效管理这些映射区域,Go 运行时把它们划分为由粗到细的几个层级。最大的单位叫作 arena,大小固定为 64 MB。运行时尽量让相邻的 arena 在地址上连续,但 mmap 系统调用可能返回与请求不同的地址,因此不能保证连续。

Each arena is further subdivided into smaller fixed-size units called pages, each measuring 8 KB. It’s important to note that these runtime-managed pages differ from the typical OS pages discussed in the fundamental post, which are commonly 4 KB in size. Each page holds multiple objects of the same size if the objects are smaller than 8 KB, or just a single object if the size is exactly 8 KB. Objects larger than 8 KB stretch over multiple pages.

每个 arena 又分成许多固定大小的页,每页 8 KB。这里说的是运行时管理的页,和前文提到的操作系统页不同,后者通常是 4 KB。如果对象小于 8 KB,一页可以容纳多个相同大小的对象;如果对象恰好为 8 KB,一页容纳一个;更大的对象要跨越多页。

Go 运行时管理的内存页
Memory pages in Go runtime
Go 运行时管理的内存页

These pages are also utilized for the allocation of goroutine stack. As discussed previously in my Go Scheduler blog post, each goroutine stack initially occupies 2 KB, meaning a single 8 KB page can house up to 4 goroutine stacks.

这些页也用于分配 goroutine 的栈。正如我在《Go 调度器》中所说,一个 goroutine 的栈初始占 2 KB,因此一张 8 KB 的页最多可以容纳四个这样的栈。

Span and Size ClassSpan 与大小类别

Another key concept in Go’s memory management is the span. A span is a unit of memory consisting of one or more contiguous pages allocated together. Each span is subdivided into multiple objects of the same size. By partitioning a span into multiple equal object, Go effectively uses segregated fit memory allocation strategy. This strategy allows Go to efficiently allocate memory for objects of various sizes while minimizing fragmentation.

Go 内存管理中的另一个关键概念是 span。一个 span 由一页或多页连续分配的页组成,内部划分成若干大小相同的对象。把相同尺寸的对象放在一起,是一种称为分类适配(segregated fit)的分配策略。这样既能高效地满足不同大小的分配请求,又能减少碎片。

Go uses the mspan struct to hold metadata about a span, such as the starting address of the first page, the number of pages it spans, the number of allocated objects, and more. In this blog, when I refer to a span, I mean the memory region it represents. When I refer to an mspan, I mean the struct that describes that region.

Go 用 mspan 结构体保存 span 的元数据,包括首页起始地址、页数和已分配对象数等。文中说 span 时,指这片内存区域;说 mspan 时,指描述这片区域的结构体。

The Go runtime organizes object sizes into a set of predefined groups called size classes. Every span belongs to exactly one size class, determined by the size of objects it contains. Go defines 68 distinct size classes, numbered from 0 to 67, as shown in this size class table. Size class 0 is reserved to handle allocation for large objects, which is larger than 32 KB, while size class 1 to 67 are used for tiny objects and small objects.

运行时预先把对象大小分成若干组,称为大小类别(size class)。每个 span 只属于一个大小类别,由它所容纳的对象大小决定。如大小类别表所示,Go 总共定义了 68 个类别,编号从 0 到 67。类别 0 留给超过 32 KB 的大对象;类别 1 至 67 用于微小对象和小对象。

两个大小类别不同的 span
Two spans with different size classes
两个大小类别不同的 span

Spans belonging to some size class contain a fixed number of pages and objects, determined by the bytes/span and objects columns in the table. The figure above illustrates two spans: one from size class 38 (holding 2048-byte objects) and another from size class 55 (holding 10880-byte objects). Because a single 8 KB page fits exactly four 2048-byte objects, the span for size class 38 contains 4 objects within a single page. Conversely, since each 10880-byte object exceeds one page, the span for size class 55 spans 4 pages, accommodating 3 objects.

同一大小类别的 span 包含固定数量的页和对象,可从表中的 bytes/span 和 objects 两列看出。上图中,一个 span 属于类别 38,每个对象 2048 字节;另一个属于类别 55,每个对象 10880 字节。一张 8 KB 的页恰好能放下四个 2048 字节的对象,所以类别 38 的 span 只需一页。10880 字节则超过一页,类别 55 的 span 用四页容纳三个对象。

But why doesn’t a span of size class 55 contain only one object and stretch over 2 pages, as described in the below figure? The reason is to reduce memory fragmentation. Since objects within a span are contiguous, there could be a space between the last object and the end of the span. This space is called tail waste, and can be easily determined by the formula (number of pages)*8192-(number of objects)*(object size). If the span were allocated across 2 pages, the tail waste would be 2*8192-10880*1=5504 bytes, significantly higher than the 4*8192-10880*3=128 bytes of tail waste when allocated across 4 pages.

为什么类别 55不像下图那样,用两页放一个对象?原因是要减少内存碎片。span 内的对象连续排列,最后一个对象与 span 末尾之间可能留下一段用不上的空间,称为尾部浪费。浪费的字节数等于 页数 × 8192 − 对象数 × 对象大小。如果采用两页方案,尾部浪费为 2*8192-10880*1=5504 字节,远多于四页方案的 4*8192-10880*3=128 字节。

Span 的尾部浪费
Tail waste in span
Span 的尾部浪费

While a user Go application can allocate objects of various sizes, why does Go have only 67 size classes for small objects? What if our application allocates a small object of size 300 bytes, which doesn’t have a corresponding entry in ths size classes table? In such case, Go runtime will round up the size of the object to the next size class, which is 320 bytes in this case. The green object illustrated so far is not an actual object allocated by user Go application, but rather a size class object managed by the Go runtime.

应用可以请求各种大小的对象,为什么 Go 只为小对象设置了 67 个类别?如果申请一个 300 字节的对象,而大小类别表里没有这一项,会发生什么?运行时会向上取整到下一个大小类别,这里是 320 字节。前面图中的绿色方块表示运行时按大小类别管理的对象槽位,和用户程序实际申请的对象还有一层区别。

用户对象与大小类别对应的对象槽位
User objects and size class objects
用户对象与大小类别对应的对象槽位

Objects allocated by user Go application (abbreviated by user objects) are contained within a size class object. User objects can vary in size, but they must be smaller than the size of the size class object that they belong to. Because of this, there could be a waste between the size of the user object and the size of the size class object. These wastes in all size class objects together with the tail waste constitutes the total waste of the span.

Go 应用申请的对象(简称用户对象)存放在这些槽位中。用户对象大小不一,但不能超过槽位容量。因此,用户对象末尾与槽位末尾之间也可能有空隙。把所有槽位中的空隙与 span 的尾部浪费加起来,就是这个 span 浪费的总空间。

⚠️ A size class object does not always contain exactly one user object. For small & large user objects, each size class object typically holds exactly one user object. For tiny user objects, however, multiple user objects can be packed into a single size class object, see Tiny Objects Allocator.

⚠️ 一个槽位并非总是只存放一个用户对象。对于小对象和大对象,通常是一个槽位放一个;多个微小对象却可能被装进同一槽位,详见微小对象分配器。

Let’s consider a span of size class 55 in the worst-case scenario, where it holds three user objects, each with a size of 10241 bytes, i.e. the minimum size for objects of size class 55. The waste of 3 size class objects is 3*(10880-10241)=3*639=1917 bytes, and the tail waste is 4*8192-10880*3=128 bytes. Therefore, the total waste of this span is 1917+128=2045 bytes, while the span size is 4*8192=32768 bytes, resulting in the maximum total waste of 2045/32768=6.24%, as described in the 6th column of the size class 55 in Go’s size class table.

以类别 55为例。最不利的情况是 span 中的三个用户对象都是 10241 字节,也就是落入该类别的最小尺寸。三个槽位合计浪费 3*(10880-10241)=3*639=1917 字节,尾部又浪费 4*8192-10880*3=128 字节。总共浪费 1917+128=2045 字节;整个 span 是 4*8192=32768 字节,最大浪费比例为 2045/32768=6.24%,正好对应 Go 大小类别表中类别 55 的第六列。

Despite the fact that Go uses segregated fit strategy, which is designed to minimize fragmentation, there is still some waste in the memory. The total waste of a span reflects how much memory is externally fragmented per span.

Go 采用分类适配来减少碎片,仍然会浪费一些内存。把上述两部分加在一起,就能看出每个 span 有多少空间因碎片而没有用于存放用户数据。

Span ClassSpan 类别

Go’s garbage collector is a tracing garbage collector, which means it needs to traverse the object graph to identify all reachable objects during a collection cycle. However, if a type is known to contain no pointers neither directly nor through its fields, e.g. a struct that has multiple fields and some of the fields contain pointer to primitive types or pointer to another struct, then the garbage collector can safely skip scanning objects of that type to reduce overhead and improve performance, right? The presence or absence of pointers in a type is determined at compile time, so this optimization comes with no additional runtime cost.

Go 的垃圾收集器是追踪式收集器,每轮收集都要遍历对象图,找出所有可达的对象。如果编译器知道某个类型不含指针,连嵌套字段中也没有指针,那么 GC 就可以跳过对该类型对象的扫描,以减少开销。反过来,结构体中指向基本类型或其他结构体的字段,都需要考虑。类型是否含指针在编译期就已确定,这一优化不会带来额外的运行时判断成本。

To facilitate this behavior, the Go runtime introduces the concept of a span class. A span class categorizes memory spans based on two properties: the size class of the objects they contain and whether those objects include pointers. If the objects contain pointers, the span belongs to the scan class. If they don’t, it’s classified as a noscan class.

为了区分这两种情况,运行时引入了 span 类别(span class),根据两个属性给 span 分类:对象的大小类别,以及对象中是否含指针。含指针的属于 scan 类,不含指针的属于 noscan 类。

Because pointer presence is a binary property—either a type contains pointers or it doesn’t—the total number of span classes is simply twice the number of size classes. Go defines 68*2=136 span classes in total. A span class is represented by an integer, ranging from 0 to 135. If the number is even, it is a scan class; noscan class otherwise.

有没有指针只有两种可能,所以 span 类别的数量正好是大小类别数的两倍。Go 定义了 68*2=136 个 span 类别,由 0 至 135 的整数表示。偶数代表 scan,奇数代表 noscan。

Previously, I mentioned that every span belongs to exactly one size class. More accurately, however, every span belongs to exactly one span class. The associated size class can be derived by dividing the span class number by 2. Whether the span belongs to scan or noscan class is determined by the parity of the span class number: even numbers indicate scan spans, while odd numbers indicate noscan spans.

前面说每个 span 都属于一个大小类别。更准确地说,每个 span 都属于一个确定的 span 类别。将该类别的编号整除以 2 就能得到大小类别,再看奇偶性就知道是否需要扫描:偶数需要,奇数不需要。

Span SetSpan 集合

In order to manage spans efficiently, Go runtime organizes them into a data structure called span set. A span set is a collection of mspan objects that belong to the same span class, illustrated in the figure below.

为了高效管理 span,Go 运行时将它们组织成 span 集合(span set)。一个集合里保存属于同一 span 类别的 mspan,如下图所示。

Span 集合的布局
Layout of a span set
Span 集合的布局

In essence, it’s a slice of arrays. The slice grows dynamically as needed, and the size of each array is fixed at 512 entries. Each element in the array is a mspan object which holds metadata for the span, and thus can be null. The purple elements in the figure above are non-null, while the white elements are null.

从结构上看,这是由切片组织的一组数组。切片按需增长,每个数组固定有 512 个条目,每个条目存放指向 mspan 的指针,后者保存 span 的元数据。指针可以为空。在上图中,紫色条目非空,白色条目为空。

A span set also have two additional fields: head and tail, which are used to track the first and last non-null elements in the span set. Popping from the span set begins at head, traversing arrays top-down and within each from left to right. Pushing begins at tail, likewise traversing top-down, filling each array from left to right. In case pushing or popping elements result in an empty array, the array is removed from the span set and added to a pool of free arrays for future reuse.

集合还有 head 和 tail 两个字段,跟踪非空条目所在区间的首尾。弹出时从 head 开始,在图中自上而下遍历数组,每个数组内自左向右;推入时从 tail 开始,遍历方向相同。若某个数组已被取空,就从集合移除,放进空闲数组池,以后还可以复用。

Note that head and tail are atomic variables, therefore adding or removing spans from the span set can be done concurrently by multiple goroutines without additional locking.

head 和 tail 是原子变量,因此多个 goroutine 能并发地向集合添加 span 或从中移除 span,无须为这些索引操作另外加锁。

Heap Bits and Malloc Header堆位图与分配头

Given a big struct having 1000 fields, some of the fields are pointers, how does Go’s garbage collector know which fields are pointers so that it can traverse the object graph correctly? If the garbage collector had to inspect every field of every object at runtime, it would be prohibitively inefficient, especially for large or deeply nested data structures. To solve this, Go uses metadata to efficiently identify pointer locations without scanning all fields. This mechanism is based on two key structures: heap bits and malloc headers.

假设有个结构体包含 1000 个字段,其中一部分是指针。GC 如何知道该跟随哪些字段,才能正确遍历对象图?如果每次收集都在运行时逐个检查每个对象的所有字段,对于庞大或嵌套很深的数据结构,成本将难以承受。Go 用元数据直接标出指针位置。这里有两种关键结构:堆位图(heap bits)和分配头(malloc header)。

For objects smaller than 512 bytes, Go allocates memory in spans and uses a heap bitmap to track which words in the span contain pointers. Each bit in the bitmap corresponds to a word (typically 8 bytes): 1 indicates a pointer, 0 indicates non-pointer data. The bitmap is stored at the end of the span and shared by all objects in that span. When a span is created, Go reserves space for the bitmap and uses the remaining space to fit as many objects as possible.

对于小于 512 字节的对象,Go 使用 span 分配内存,并用堆位图标明 span 中哪些机器字保存指针。位图的每一位对应一个机器字(通常是 8 字节):1 表示指针,0 表示非指针数据。位图放在 span 尾部,供其中所有对象共用。运行时创建 span 时先留出位图空间,再用其余空间尽可能多地容纳对象。

Span 尾部的堆位图
Heap bits in a span
Span 尾部的堆位图

For objects larger than 512 bytes, maintaining a big bitmap is inefficient. Instead, each object is accompanied by an 8-byte malloc header—a pointer to the object’s type information. This type metadata includes the GCData field, which encodes the pointer layout of the type. The garbage collector uses this data to precisely and efficiently locate only the fields that contain pointers when traversing the object graph.

对于大于 512 字节的对象,维护大位图的效率不高。另一种做法是给每个对象配一个 8 字节的分配头,其中保存指向该对象类型信息的指针。类型元数据的 GCData 字段编码了指针布局,垃圾收集器因此能在遍历对象图时准确、高效地定位指针字段。

对象的分配头
Malloc header in objects
对象的分配头

Heap Management堆管理

Go builds its own heap abstraction on top of memory-mapped segments, managed by the global mheap object. mheap is responsible for allocating new spans, sweeping unused spans, and even managing goroutine stacks.

Go 在内存映射区域之上建立自己的堆,由全局 mheap 对象管理。mheap 负责分配新的 span、清扫未使用的 span,还参与管理 goroutine 栈。

Span Allocation: mheap.alloc分配 span:mheap.alloc

Since the Go runtime operates within a vast virtual address space, the mheap allocator can struggle to locate contiguous free pages efficiently when it comes to allocating a span, especially under high concurrency. In early versions of Go, as detailed in the Scaling the Go Page Allocator proposal, every mheap operation was globally synchronized. This design caused severe throughput degradation and increased tail latency during heavy allocation workloads. Today’s Go memory allocator implements the scalable design from that proposal. Let’s dive into how it overcomes these bottlenecks and manages memory allocation efficiently in highly concurrent environments.

Go 运行时面对的虚拟地址空间非常大。分配 span 时,mheap 需要从中找到连续空闲页,高并发时尤其困难。按《让 Go 页分配器可扩展》设计提案的描述,早期版本中每次 mheap 操作都要经过全局同步。分配负载很高时,吞吐量会严重下降,尾延迟也会上升。如今的 Go 内存分配器已经实现了提案中的可扩展设计。接下来看看它如何避开这些瓶颈。

Tracking Free Pages跟踪空闲页

Because the virtual address space is large, and each page’s state (free or in-use) is a binary property, it is efficient to store this information in a bitmap where 1 represents in-use and 0 represents free. Note that in-use or free in this context refers to whether the page is owned by a span or not, not whether it is in-use or free by the user Go application. Each bitmap is an array of 8 uint64 values, taking 64 bytes in total, and can represent the state of 512 contiguous pages.

虚拟地址空间很大,而每一页只有空闲与占用两种状态,用位图记录最为紧凑:1 表示占用,0 表示空闲。这里的“占用”指页已经归某个 span 所有,和用户程序是否正在使用其中的空间是两回事。每张位图由 8 个 uint64 组成,共 64 字节,能记录 512 个连续页的状态。

Given that an arena is 64 MB in size and each page is 8 KB, there are 64MB/8KB=8192 pages in an arena. Since each bitmap covers 512 pages, an arena requires 8192/512=16 bitmaps. With each bitmap taking 64 bytes, the total size of all bitmaps for an arena is 16×64=1024 bytes, or 1 KB.

一个 arena 为 64 MB,一页为 8 KB,所以每个 arena 有 64MB/8KB=8192 页。一张位图覆盖 512 页,因此一个 arena 要用 8192/512=16 张位图。每张占 64 字节,合计 16×64=1024 字节,也就是 1 KB。

However, iterating through a bitmap to find a run of free pages is still inefficient, and wasteful if the bitmap doesn’t contain any free pages. It’s better if we somehow cache the free pages so that we can quickly find a free page without scanning the bitmap. Go introduces the concept of summary for a bitmap, which has three fields: start, end, and max. start is the number of contiguous 0 bits at the beginning of a bitmap. Similarly, end is the number of contiguous 0 bits at the end of the bitmap. Finally, max represents the largest contiguous sequence of 0 bits. The summaries are updated eagerly as soon as the bitmap is modified, i.e. when a page is allocated or freed.

要寻找一段连续空闲页,逐位扫描仍然不够快;如果整张位图恰好没有空闲页,就白扫了一遍。可以预先记下空闲区间的信息,让分配器免于反复扫描。Go 为每张位图维护一份摘要,含 start、end 和 max 三个字段。start 是开头连续 0 的个数,end 是结尾连续 0 的个数,max 是整张图中最长连续 0 串的长度。分配或释放页会修改位图,摘要也随之立即更新。

The figure below shows a bitmap summary: there are 3 contiguous free pages at the beginning, 7 contiguous free pages at the end, and the longest run of free pages is 10. The arrow indicates the growth direction in address space, i.e. 3 free pages at the lower address and 7 free pages at the higher address.

下图的位图开头有 3 个连续空闲页,结尾有 7 个,最长一段有 10 个。箭头指向地址增大的方向,所以开头的 3 页位于低地址,结尾的 7 页位于高地址。

一张位图的空闲页摘要
Visualization of a bitmap summary
一张位图的空闲页摘要

With these three fields, Go is able to find a sufficient contiguous free chunk of memory within a single arena or across multiple adjacent arenas by merging the summaries of contiguous memory chunks. Consider two adjacent chunks, S1 and S2, each spanning 512 pages. The summary of S1 is start=3, end=7, and max=10, while the summary of S2 is start=5, end=2, and max=8. Since these chunks are contiguous, they can be merged into a single summary covering all 1024 pages. The merged one is computed as start=S1.start=3, end=S2.end=2, max=max(S1.max, S2.max, S1.end+S2.start)=max(10, 8, 7+5)=12.

合并相邻内存块的摘要,就能用这三个字段寻找足够长的连续空闲区间,即便它跨越相邻 arena。假设 S1 和 S2 是两个相邻的块,各有 512 页。S1 的摘要为 start=3、end=7、max=10;S2 的摘要为 start=5、end=2、max=8。合并后的摘要覆盖 1024 页:start=S1.start=3,end=S2.end=2,而 max=max(S1.max, S2.max, S1.end+S2.start)=max(10, 8, 7+5)=12。最长的一段恰好跨过两块的交界。

合并两个相邻内存块的摘要
Merging summaries of two contiguous memory chunks
合并两个相邻内存块的摘要

By merging lower-level summaries, Go implicitly builds a hierarchical structure that enables efficient tracking of contiguous free pages. It manages the entire virtual address space using a single global radix tree of summaries as depicted in the figure below. Each blue box represents a summary for a contiguous memory chunk and its dotted lines to the next level reflects what portion in the next level it covers. The green box represents the bitmap of 512 pages that a leaf node summary refers to.

逐级合并底层摘要,就形成了一种可以高效跟踪连续空闲页的层级结构。如下图所示,Go 用一棵全局的基数树管理整个虚拟地址空间的摘要。每个蓝色方框是一个连续内存块的摘要,向下的虚线标出它覆盖的下一级范围。绿色方框是叶节点所概括的位图,一张位图对应 512 页。

覆盖整个地址空间的摘要基数树
Radix tree of summaries for the entire address space
覆盖整个地址空间的摘要基数树

On linux/amd64 architecture, Go uses a 48-bit virtual address space, which is 2^48 bytes or 256 TB. In this setup, the radix tree has a height of 5. Internal nodes (levels 0 to 3) store summaries derived from merging their 8 child nodes. Each leaf node (level 4) corresponds to the summary of a single bitmap, which covers 512 pages.

在 linux/amd64 上,Go 使用 48 位虚拟地址空间,即 2^48 字节或 256 TB。在这种配置下,基数树共五层。内部节点(第 0 至 3 层)存放其八个子节点合并后的摘要;每个叶节点(第 4 层)对应一张位图的摘要,覆盖 512 页。

There are 16384 entries at level 0, 16384*8 entries at level 1, 16384*8^2 entries at level 2, 16384*8^3 entries at level 3, and 16384*8^4 entries at level 4. Because each leaf entry summarizes 512 pages, each level 0 entry summarizes 512*8^4=2097152 contiguous pages, which accommodates 2097152*8KB=16GB amount of memory. Note that these numbers represent the maximum possible entries. The actual number of entries at each level increases gradually as the heap grows.

第 0 层有 16384 项,第 1 层有 16384*8 项,第 2 层有 16384*8^2 项,第 3 层有 16384*8^3 项,第 4 层有 16384*8^4 项。每个叶节点涵盖 512 页,因此第 0 层的每个条目涵盖 512*8^4=2097152 个连续页,即 2097152*8KB=16GB 内存。这些是各层可能达到的最大条目数;实际使用的条目会随堆增长逐步增加。

摘要基数树各层的覆盖范围
A deeper look into the summary radix tree
摘要基数树各层的覆盖范围

As mentioned earlier, each level 0 entry summaries 209715=2^21 contiguous pages, start, end, and max can be as big as 2^21. As a result, storing all these three fields together requires up to 21*3=63 bits. This makes it possible to pack a summary into a single uint64 called pallocSum: the first 21 bits store start, the next 21 bits store end, and the following 21 bits store max.

如上文算得,第 0 层的每个条目涵盖 2^21(2,097,152)个连续页,start、end 和 max 的最大值均可达到 2^21。除下一段的特殊情况外,每个字段用 21 位就够,三者合起来是 21*3=63 位。因此一份摘要可以打包进一个名为 pallocSum 的 uint64:前 21 位存 start,接下来 21 位存 end,再用 21 位存 max。

There is one special case: if max=2^21, it means the entire chunk is free. In this situation, start and end are also 2^21, and the summary is encoded as 2^63. Conversely, if the chunk has no free page, i.e. all start, end and max are 0, the summary value is definitely 0.

特殊情况是 max=2^21,这表示整块都空闲,此时 start 和 end 也都是 2^21。运行时把这份摘要编码为 2^63。反过来,如果一块里没有任何空闲页,三个字段就全是 0,整个摘要的值也是 0。

The summary radix tree is implemented as an array of slices, where each slice corresponds to a tree level. The array fixes the number of levels in the tree, while the slices grow dynamically as the heap expands. Summaries for the lower address stays at the beginning of the slice, while summaries for the higher address are appended to the end of the slice. Since the summary slice at a given level covers the entire reserved address space, the index of a summary within its slice directly determines the memory region it represents.

摘要基数树的实现是一个由切片组成的数组,每个切片对应一层。数组长度固定了树的层数,每层切片可随堆扩展而增长。低地址的摘要在切片前部,高地址的追加在末尾。每层切片都覆盖相应的预留地址空间,因此条目在切片中的下标就能直接确定它所描述的内存区域。

Finding Free Pages: pageAlloc.find查找空闲页:pageAlloc.find

Go uses depth-first search algorithm locate a sufficient run of free pages. It begins with scanning up to 16,384 entries at level 0 of the radix tree. If a summary is 0 (meaning no free pages), it moves on to the next entry. If a sufficient run is found at the boundary between two adjacent entries, or at the start of the first entry, or at the end of the last entry, then it returns the address of the free run immediately, based on the address the summary refers to.

Go 采用深度优先搜索寻找足够长的连续空闲页。先从第 0 层开始,最多检查 16,384 个条目。摘要为 0,说明没有空闲页,直接跳到下一项。如果在相邻两项的交界处、第一项的开头或最后一项的结尾已经找到足够长的一段,就根据摘要对应的地址直接返回该段的起始地址。

Otherwise, if current summary’s max field satisfies the allocation request, the search descends into its 8 child entries at the next level. If the search reaches the leaf level but still can’t find a sufficient run, then it scans the bitmap within the entry whose max value is large enough, in order to locate the exact run of free pages. If we traverse all entries at level 0 but still can’t find a sufficient run, it returns 0, indicating no free pages.

否则,如果当前摘要的 max 足以满足请求,就下探到下一层的八个子条目。到达叶层后,如果还不能确定空闲段的确切位置,就扫描 max 足够大的那个条目对应的位图。如果第 0 层都找遍了,仍没有满足长度要求的区间,就返回 0,表示本次请求没有找到可用页。

You may notice a drawback in this algorithm: if many pages at the beginning of level 0 are already in use, the allocator ends up traversing the same path in the radix tree repeatedly for each allocation, which is inefficient. Go addresses this by maintaining a hint called searchAddr, which marks an address before which no free pages exist. This allows the allocator to begin its search directly from the hint instead of restarting from the beginning.

这个算法有个明显的不足:如果低地址的许多页早已被占用,每次分配都会重复走过基数树中同一段无效路径。Go 为此维护一个提示地址 searchAddr,表示它之前没有可分配的空闲页。下一次可以直接从提示处开始查找。

Since allocations proceed from lower to higher addresses in the heap, the hint can be advanced after each search, shrinking the search space until new memory is freed. In practice, most allocations occur close to the current hint.

堆分配从低地址向高地址推进,每次查找后都可以相应地推进提示地址,缩小后续的搜索空间,直到又有内存被释放。实际上,大多数分配都发生在当前提示地址附近。

Growing the Heap: mheap.grow扩展堆:mheap.grow

If no free pages are available in the radix tree, i.e. pageAlloc.find returns 0, Go runtime must ask the kernel to expand its virtual address space by making an mmap system call. The growth may not be as big as the number of pages requested, but instead occurs in larger chunks rounded up to the arena size (64 MB). Even if only a single page is requested, the heap expands by 64 MB in virtual memory space (not physical, thanks to demand paging!).

如果在基数树里找不到可用页,即 pageAlloc.find 返回 0,运行时就必须通过 mmap 系统调用向内核申请新的虚拟地址空间。扩展时会按 arena 大小(64 MB)向上取整,因而可能远大于请求的页数。即使只请求一页,也可能扩展 64 MB 的虚拟地址空间;物理内存则受益于按需分页,无须同时增加这么多。

To manage this, the runtime maintains a list of hint addresses called arenaHints, which are addresses it prefers the kernel to use for new allocations. This list is initialized before the main function runs, and its values can be found here. During heap growth, Go iterates through these hints, asking the kernel to allocate memory at each suggested address by passing that address to the first parameter of mmap system call.

运行时维护一个叫作 arenaHints 的候选地址列表,希望内核优先从这些位置分配新区域。列表在 main 执行之前初始化,取值见源码。扩展堆时,Go 依次尝试这些地址,将每一个作为 mmap 的第一个参数传给内核。

The kernel, however, may choose a different location. If that happens, Go moves on to the next hint. If all hints fail, Go falls back to requesting memory at a random address aligned to the arena size, and then updates the hint list so that the future growth stays contiguous with the newly allocated arena.

内核可能选中别的位置。如果返回地址不合预期,Go 就尝试下一个候选。所有候选都失败时,Go 会退而申请一段按 arena 大小对齐、地址由系统选择的内存,再更新提示列表,使后续增长尽可能与这块新 arena 连续。

This process transitions the memory section from None to Reserved. Once the arena is registered with the runtime, i.e. by being added to the list of all arenas, the section transitions from Reserved to Prepared. At this point, the radix summary tree is updated to include the new arena, expanding the summary slices at each level, marking the bitmap for new pages as free, and update the summaries accordingly. This new memory section is also tracked as in-use.

这个过程让内存区域由 None 变为 Reserved。将新 arena 登记到运行时,即加入全部 arena 列表后,区域再从 Reserved 变为 Prepared。随后更新摘要基数树:按需扩展每层切片、在位图中把新页标为空闲,并更新相应的摘要。这段新内存也会纳入已使用地址范围的记录。

Setting up a Span: mheap.haveSpan设置 span:mheap.haveSpan

Once the requested run of pages is found, the runtime sets up an mspan object to manage that memory range. Like any other Go object, an mspan object itself must live in memory. Thus, these mspan objects are allocated by a fixalloc slab allocator, which requests memory directly from the kernel using mmap system call.

找到请求的连续页之后,运行时需要一个 mspan 对象管理这段内存。mspan 对象本身也要占用内存。这些 mspan 元数据由 fixalloc 这个固定大小的 slab 分配器分配,其底层通过 mmap 系统调用直接向内核申请内存。

The span is then set up with its size class, the number of pages it covers, and the address of its first page. The associated memory section transitions from Prepared to Ready, indicating that it’s ready for mcentral to use.

然后为 span 设置大小类别、覆盖的页数及首页地址。对应的内存区域从 Prepared 转入 Ready,表示 mcentral 已经可以使用它。

Caching Free Pages: mheap.allocToCache缓存空闲页:mheap.allocToCache

Unfortunately, both pageAlloc.find and mheap.grow rely on global locks, which can become bottlenecks under heavy concurrent allocation workloads. Since a Go program runs as concurrent as the number of processor Ps, caching free pages locally in each P helps avoid global lock contention.

pageAlloc.find 和 mheap.grow 都依赖全局锁,在大量并发分配时可能形成瓶颈。由于 Go 代码的并行程度受逻辑处理器 P 数量限制,把空闲页缓存在各个 P 上就能减少对全局锁的争用。

Go implements this with a per-P pageCache. A pageCache consists of a base address for a 64-page-aligned memory chunk and a 64-bit bitmap tracking which of those pages are free. Because each page is 8 KB, a single P’s pageCache can hold up to 512 KB of free memory.

为此,每个 P 都配有 pageCache。一个 pageCache 包含按 64 页对齐的内存块的基址,以及一张 64 位位图,用来记录块内哪些页空闲。每页 8 KB,因此单个 P 的 pageCache 最多可以缓存 512 KB 空闲内存。

When a goroutine requests a span from mheap, the runtime first checks the pageCache of the current P. If it contains enough free pages, those pages are used immediately to set up a span. If not, the runtime falls back to invoking pageAlloc.find to locate a sufficient run of pages.

goroutine 向 mheap 请求一个 span 时,运行时先查当前 P 的 pageCache。如果其中有足够长的一段连续空闲页,就直接用这些页设置 span;否则才调用 pageAlloc.find 查找。

If the pageCache is empty, the runtime allocates a new one. It first tries to obtain pages near the current hint searchAddr in the summary radix tree (as described in Finding Free Pages section). Since the hint may not be accurate, it may instead need to walk the radix tree to find free pages.

如果 pageCache 已空,运行时就要重新填充它。首先尝试从摘要基数树当前的提示地址 searchAddr 附近取页,详见查找空闲页。提示地址未必恰好有空闲页,必要时仍需遍历基数树。

Note that the probability of having a N free pages decreases when N approaches 64, as the pageCache is limited to 64 pages. In such case, there would be too many cache misses, and the runtime would have to frequently fall back to pageAlloc.find to find free pages. That’s why if N is equal to or greater than 16, the runtime doesn’t bother checking the cache, and fallback to pageAlloc.find right away.

pageCache 总共只有 64 页,所以所需连续页数 N 越接近 64,缓存命中的可能性就越低。频繁的未命中只会导致运行时一再退回 pageAlloc.find。为此,N 大于或等于 16 时,运行时直接调用 pageAlloc.find,跳过缓存检查。

The diagram below summarizes the logic for finding free pages for span allocation. The gray box Find pages was described in Finding Free Pages section, the green box Grow the heap was described in Growing the heap section, while the blue box Set up a span was described in Set up a Span section.

下图串起了为 span 查找空闲页的流程。灰色的 Find pages 对应查找空闲页,绿色的 Grow the heap 对应扩展堆,蓝色的 Set up a span 对应设置 span。

为 span 分配连续空闲页的流程
Logic for finding free pages for span allocation
为 span 分配连续空闲页的流程

Once new pages are acquired, they are marked as in-use in the summary radix tree to prevent other Ps from claiming them and to ensure the allocator does not reuse them on the next heap growth. The summary radix tree hint is also updated so that subsequent allocations skip over these pages, which are in-use.

取得新页后,运行时会在摘要基数树中将其标为已占用,避免其他 P 再次认领,也避免分配器在下次扩展堆时重复使用。提示地址随之更新,让后续分配跳过这些页。

Caching Span Objects: mheap.allocMSpanLocked缓存 span 描述对象:mheap.allocMSpanLocked

As discussed in Set up a Span, an mspan object must be allocated to represent and manage a span of pages. If an mspan object is obtained directly from mheap, it requires acquiring a global lock, which can become a performance bottleneck. To avoid this, the Go runtime caches free mspan objects per P, just like pages.

如设置 span所述,需要分配 mspan 对象来描述并管理一段连续页。如果每次都从 mheap 直接获取 mspan,就需要拿全局锁,可能成为性能瓶颈。Go 因此像缓存页一样,在每个 P 上缓存空闲的 mspan 对象。

When free pages are found in a pageCache, the runtime first checks whether the current P already has a cached mspan. If so, it can be reused immediately without any global lock contention. Otherwise, the runtime allocates multiple mspan objects from mheap, caches them in the P’s free list for future use, and assigns one of them to manage the newly allocated run of pages.

在 pageCache 中找到空闲页后,运行时先检查当前 P 是否已有缓存的 mspan。有的话可以立即复用,无须争用全局锁。否则,从 mheap 批量分配多个 mspan,放入 P 的空闲列表供以后使用,其中一个立即用来管理刚分到的连续页。

Central Span Manager: mcentral中央 span 管理器:mcentral

Since mheap primarily manages coarse-grained units of memory such as pages and large spans, it does not provide an efficient way to allocate and free tiny or small objects. That role is handled by mcentral, which also serves as the bridge between mheap and per-P allocators mcache (discussed in Process’s Memory Allocator).

mheap 主要管理页和大段连续空间这样的粗粒度单位,并不适合直接分配、释放微小对象或小对象。这项职责属于 mcentral,它也是 mheap 和每个 P 的分配器 mcache 之间的桥梁,后者详见处理器的内存分配器。

Internal Data Structure内部数据结构

Each mcentral manages spans belonging to a specific span class. In total, mheap maintains 136 mcentral instances—one for each class. Within an mcentral, there are two categories of span sets: full (spans with no free objects) and partial (spans with some free objects). Each category is further divided into two span sets: swept and unswept, depending on whether the spans have been swept or not.

每个 mcentral 管理一个指定 span 类别的所有 span。mheap 共维护 136 个 mcentral 实例,每个类别一个。每个 mcentral 内的 span 集合先按可用空间分为两组:full,其中的 span 已无空槽位;partial,其中的 span 还有空槽位。这两组再根据 span 在当前清扫周期是否已被清扫,各分为 swept(已清扫)和 unswept(未清扫)两个集合。

一个 mcentral 实例中的 span 集合
Span sets in a mcentral instance
一个 mcentral 实例中的 span 集合

What does it mean for a span to be swept? Go’s garbage collector is based on mark-and-sweep: first marking all reachable objects, then sweeping away the unreachable ones, either returning that memory to the runtime for reuse or, in some cases, releasing it back to the kernel to reduce the process footprint. Sweeping is a complex process, but in essence includes the following three steps: popping a span from the unswept set, freeing objects that have been marked as unreachable in that span, and pushing the span into the swept set.

span 被“清扫”究竟是什么意思?Go 的垃圾收集器采用标记—清扫算法,先标出所有可达对象,再清理不可达对象所占空间,使运行时可以复用内存;在某些情况下,还能把内存还给内核、减小进程占用。清扫的细节较复杂,主要步骤是从未清扫集合弹出一个 span、释放其中已判定为不可达的对象,再把 span 放入已清扫集合。

A span transition between the partial and full is determined during allocation or sweeping, depending on whether the number of free objects in the span increases or decreases. If the number of free objects in a span reaches zero, it is moved from the partial set to the full set. Otherwise, if the number of free objects in a span is positive, it is moved from the full to the partial set.

分配和清扫会改变 span 的空闲槽位数,也决定它在 partial 和 full 之间的流转。如果最后一个空槽位也被用掉,span 就从 partial 移入 full。如果原来已满的 span 出现空槽位,就从 full 移入 partial。

Since span sets are thread-safe as discussed in Span Set, an mcentral can be accessed concurrently by multiple goroutines without additional locking. Thus increases the throughput of span allocation of Go programs.

如Span 集合一节所述,span 集合可供多个线程安全访问,因此多个 goroutine 可以并发访问同一个 mcentral,无须再用一把锁把整个管理器串行化。这提高了 Go 程序分配 span 的吞吐量。

Preparing a Span: mcentral.cacheSpan准备 span:mcentral.cacheSpan

As the intermediate between mheap and mcache, an mcentral is responsible for preparing span—either existing its span sets or requested from mheap—to the requesting mcache. To illustrate, this logic is detailed in the following flowchart. Logic of the green box Request mheap to allocate a span was described in Span Allocation.

mcentral 位于 mheap 和 mcache 之间,负责为提出请求的 mcache 准备一个 span:可以从已有集合中取出,也可以向 mheap 申请新的。流程如下图。绿色的 Request mheap to allocate a span 方框,展开后就是分配 span一节介绍的逻辑。

mcentral 准备 span 的流程
Logic for preparing a span by mcentral
mcentral 准备 span 的流程

Collecting a Span: mcentral.uncacheSpan收回 span:mcentral.uncacheSpan

When a mcache needs to return a span back to a mcentral, it invokes mcentral.uncacheSpan method. If a span hasn’t been swept, it is swept first to reclaim unreachable objects. Then regardless of whether sweeping was needed, the span is placed into either full or partial swept set, depending on its number of free objects.

mcache 需要向 mcentral 归还 span 时,调用 mcentral.uncacheSpan。如果 span 尚未清扫,先进行清扫以回收不可达对象。随后按剩余空槽位数,将它放入 full 或 partial 的已清扫集合。

Processor’s Memory Allocator: mcache处理器的内存分配器:mcache

As discussed in the Go Scheduler post, each processor P serves as the execution context for goroutines. As goroutine may allocate memory, each P also maintains its own memory allocator called mcache, which is optimized for tiny and small heap allocation, and allocating stack segment for goroutines as well.

如《Go 调度器》所述,每个逻辑处理器 P 为 goroutine 提供执行上下文。goroutine 可能需要分配内存,所以每个 P 还维护自己的内存分配器 mcache,专门优化微小对象和小对象的堆分配,也用来为 goroutine 分配栈段。

Caching Free Spans缓存有空槽位的 span

The name mcache comes from the fact that it caches spans with free objects for each span class in its alloc field. When an mcache instance is initialized, every span class is cached with an emptymspan, which contains no free objects. When a goroutine needs to allocate a user object of a specific span class, it asks mcache for a free size class object to house the requested user object—either from the cached span, or by requesting a new span from mcentral if no free object is available in the cached span. This logic is illustrated in the following diagram.

mcache 的名字源于它的缓存作用:alloc 字段为每个 span 类别保留一个有空闲槽位的 span。初始化 mcache 实例时,各类别的缓存最初都指向 emptymspan,其中没有空闲对象。goroutine 申请特定类别的用户对象时,向 mcache 要一个空槽位:优先从已缓存的 span 获取,若已用完,就向 mcentral 申请新的 span。流程如下图。

向 mcache 请求指定大小类别的空槽位
Logic for requesting a free size class object from mcache
向 mcache 请求指定大小类别的空槽位

Logic for the green box Return the cached span to mcentral was described in Collecting a Span. While logic for the blue box Request mcentral for a new span was described in Preparing a Span.

绿色方框 Return the cached span to mcentral 对应收回 span;蓝色方框 Request mcentral for a new span 对应准备 span。

Tiny Objects Allocator微小对象分配器

All user tiny objects of various sizes (smaller than 16 bytes) are allocated from a span class 5 (or size class 2), where each size class object occupies 16 bytes. Each mcache instance tracks tiny allocations in a span using 3 fields:

微小对象分配器把各种不足 16 字节的用户对象放进span 类别 5(即大小类别 2)的 span,每个槽位占 16 字节。每个 mcache 通过三个字段跟踪微小对象的分配情况。

  1. tiny: The starting address of the current size class object having available space for allocation.
    tiny:当前仍有可用空间的槽位的起始地址。
  2. tinyoffset: The end position (relative to tiny) of the last allocated user object.
    tinyoffset:上一次分配的用户对象的结束位置,用相对于 tiny 的偏移量表示。
  3. tinyalloc: Total number of user tiny objects allocated in the current span so far.
    tinyalloc:到目前为止记录的微小用户对象分配数量。
用于分配微小用户对象的 span 示例
An example span for tiny user object allocations.
用于分配微小用户对象的 span 示例

The figure above illustrates a span used for tiny object allocations, in which 0x30 is an example starting address of the size class object. The detailed allocation logic will be explained in the Tiny Objects: mallocgcTiny.

上图展示了一个用于微小对象分配的 span。图中的 0x30 是某个槽位的示例起始地址。具体分配步骤见微小对象:mallocgcTiny。

Putting it All Together串起各层分配器

As discussed in previous sections, Go’s memory allocator is a complex system with three components that work together to manage memory efficiently: mheap, mcentral, and mcache. The figure below summarizes how these components interact to allocate memory for our Go programs. Take a moment to review it before we dive into the detailed heap allocation logic in the next section.

前面几节介绍了 Go 内存分配器的三个组成部分:mheap、mcentral 和 mcache。下图把它们放回一起,展示 Go 程序申请内存时各层如何配合。可以先用这张图回顾全貌,再进入下一节的堆分配细节。

Go 内存分配器总览
Recap of memory allocator in Go
Go 内存分配器总览

Heap Allocation堆分配

In Go, it’s a common misconception that allocating an object on the heap requires new(T) or &T{}. This isn’t always the case for several reasons. First, if an object is small enough, lives only within a function’s scope, and isn’t referenced outside that scope, the compiler may allocate it on the stack instead of the heap. Second, even a primitive declared with var n int can end up on the heap, depending on escape analysis. Third, creating composite types such as slices, maps, or channels with make often places their underlying data structures on the heap.

看到 new(T) 或 &T{},不能就此断定对象会分配在堆上。首先,如果对象足够小,只在当前函数内使用,离开作用域后也没有引用保留,编译器可以把它放在栈上。其次,即便是 var n int 这样简单的变量,也可能因逃逸分析的结果而进入堆。再者,用 make 创建切片、映射或 channel 时,底层数据结构也常常分配在堆上。

The decision of allocating an object on heap is determined by the compiler, and will be described in Stack or Heap? section. This section only focuses on mallocgc—the method Go runtime uses to allocates objects on the heap. This method will be indirectly invoked by various built-in functions and operators, such as new, make, &T{}.

是否需要堆分配由编译器决定,详见栈还是堆?。这一节只看运行时用来在堆上分配对象的函数 mallocgc。new、make、&T{} 等内置操作都可能间接调用它。

mallocgc classifies objects into three categories based on their size: tiny (less than 16 bytes), small (16 bytes to 32760 bytes), and large (greater than 32760 bytes). It also considers whether the object type contains any pointers, which affects garbage collection. Based on these criteria, it invokes different allocation paths, as illustrated in the diagram below, to optimize memory usage and performance.

mallocgc 按请求大小区分微小对象(小于 16 字节)、小对象(16 至 32760 字节)和大对象(大于 32760 字节)。它也会检查对象的类型是否含指针,因为这影响垃圾收集。下图展示了如何结合这些条件选择分配路径,以兼顾内存利用率和执行效率。

mallocgc 如何选择分配路径
How mallocgc determines which allocation path to take
mallocgc 如何选择分配路径

Tiny Objects: mallocgcTiny微小对象:mallocgcTiny

Tiny objects are allocated by an mcache in every processor P, using the three properties described in Tiny Objects Allocator section. The allocation logic is described in the following diagram.

每个处理器 P 都有一个 mcache,利用微小对象分配器一节中的三个字段完成微小对象分配。具体逻辑如下图。

mallocgcTiny 的分配流程
Overview logic for mallocgcTiny
mallocgcTiny 的分配流程

The tinyoffset is aligned based on the requested size—8-byte alignment if divisible by 8, 4-byte if divisible by 4, 2-byte if divisible by 2, and no alignment otherwise. The check in the blue diamond means whether a requested user object of the requested size and starting at tinyoffset can fit into the current size class object; if so, it’s possible for a new user object to be allocated within that size class object. The logic of the green box Request a new span of span class 5 from mcentral was described in Preparing a Span section.

首先根据请求大小对齐 tinyoffset:大小能被 8 整除时按 8 字节对齐,否则依次尝试 4 字节、2 字节对齐,其余情况无须额外对齐。蓝色菱形判断从 tinyoffset 开始、长度为 size 的用户对象能否装入当前槽位。如果能,就在这个槽位内分配。绿色方框 Request a new span of span class 5 from mcentral 的逻辑见准备 span。

微小对象的分配
Allocation for tiny objects
微小对象的分配

Note that tiny object allocations are served by mcache, which is local to each processor P. This makes the allocation thread-safe and lock-free, except when a new span must be requested from mheap by mcentral.

为微小对象提供分配的是每个 P 私有的 mcache,因此本地分配既线程安全,又无须加锁。只有 mcentral 必须向 mheap 申请新 span 等情况下,才会涉及全局锁。

Spans used by tiny object allocations belong to span class 5, or size class 2. According to the size class table, a span of size class 2 accommodates 512 size class objects. Since each size class object can house multiple user objects in tiny allocation, a single span can serve at least 512 tiny user object allocations without any locks.

这类 span 属于 span 类别 5,即大小类别 2。按大小类别表,一个类别 2 的 span 可以容纳 512 个槽位。微小对象还可以共用槽位,因此准备好一个 span 后,至少可以完成 512 次微小用户对象分配而无须加锁。

Small Objects: mallocgcSmall*小对象:mallocgcSmall*

In order for the garbage collector to efficiently identify live objects and skip tracing for objects which don’t contain references to other objects, Go classifies small objects into scan and noscan span class based on whether their types contain pointers (described in Span Class section). The scan span class is further divided into two categories: those with a heap bits and those with malloc header (described in Heap Bits and Malloc Header section). Go implements different functions to allocate small objects based on these classifications.

为了让垃圾收集器高效找出存活对象,跳过不引用其他对象的内存,Go 根据类型中是否含指针,将小对象分为 scan 和 noscan 两类,见Span 类别。scan 又分为使用堆位图和使用分配头的两类,见堆位图与分配头。不同情形由不同的函数处理。

Noscan Small Objects: mallocgcSmallNoscan不含指针的小对象:mallocgcSmallNoscan

Small objects that contain no pointers are allocated by mallocgcSmallNoscan function. The requested size is first rounded up so the object fits exactly into a size class object. As the allocation is noscan, the span class is calculated as 2*sizeclass+1. For example, if a user requests an object of size 365 bytes, it is rounded up to the nearest size class of 384 bytes, or size class 22. The corresponding span class is therefore 45 (2*22+1).

mallocgcSmallNoscan 为不含指针的小对象分配内存。它先将 size 向上取整到能容纳该对象的最小槽位。由于无须扫描,span 类别为 2*sizeclass+1。例如,申请 365 字节,会向上取整到 384 字节,即大小类别 22,相应的 span 类别就是 45(2*22+1)。

The function then checks if there is a free object in the cached span of the calculated span class in the current processor P’s mcache. If none is available, it requests a free size class object by asking for a new span from mcentral and caches it in the mcache. After getting a free size class object, it updates information for the garbage collector and the profiler, and returns the address of the allocated object.

然后在当前 P 的 mcache 中,检查该 span 类别的缓存是否还有空槽位。如果没有,就向 mcentral 申请新的 span,将其放入 mcache,再从中取得空槽位。之后更新供垃圾收集器和性能分析器使用的信息,返回新分配对象的地址。

Scan Small Objects: mallocgcSmallScanNoHeader and mallocgcSmallScanHeader含指针的小对象:mallocgcSmallScanNoHeader 与 mallocgcSmallScanHeader

Depending on its size, small objects containing pointers are allocated by mallocgcSmallScanNoHeader or mallocgcSmallScanHeader function. If the requested size is less than or equal to 512 bytes, allocation is handled by the former; otherwise, it is handled by the latter. The logic of these two functions is similar to that of mallocgcSmallNoscan, except for span class, layout of span, and layout of size class objects inside the span.

含指针的小对象按大小分别由 mallocgcSmallScanNoHeader 和 mallocgcSmallScanHeader 分配。请求的 size 小于或等于 512 字节时走前者,大于 512 字节时走后者。它们的流程与 mallocgcSmallNoscan 相似,差别在于span 类别、span 自身的布局,以及 span 内部槽位的布局。

Spans used by mallocgcSmallScanNoHeader is different from ones used by mallocgcSmallNoscan—it contains a special data at its end called heap bits (see Heap Bits and Malloc Header). Since these spans must reserve space to store heap bits, they can accommodate less size class objects than what specified in the size class table. The reservation logic is implemented in mheap.initSpan method.

mallocgcSmallScanNoHeader 使用的 span 与 mallocgcSmallNoscan 的不同,尾部要存放堆位图(见堆位图与分配头)。由于必须留出这块空间,实际能容纳的槽位可能比大小类别表中列的少。预留空间的逻辑在 mheap.initSpan 中。

The layout of size class objects inside a span used by mallocgcSmallScanHeader is special as well—each size class object has a malloc header (see Heap Bits and Malloc Header) prepended to it. Therefore, in order for the user object and malloc header to fit exactly into a size class object, the requested size is increased by 8 bytes before rounding up to the nearest size class. For example, suppose Go code requests an object of 636 bytes that contains pointers. Although this would normally fit in size class 28 (640 bytes), the fact that this object contains pointers requires a malloc header, increasing the size to 644 bytes. This pushes the allocation into size class 29 (704 bytes).

mallocgcSmallScanHeader 使用的槽位也有特殊布局:每个槽位开头多了一个分配头(见堆位图与分配头)。为了让用户对象和分配头一起装进槽位,要先将请求的 size 加 8 字节,再向上取整到最近的大小类别。例如,一个含指针的对象大小为 636 字节,本可以放进类别 28的 640 字节槽位;加上分配头后是 644 字节,就必须使用类别 29的 704 字节槽位。

Large Objects: mallocgcLarge大对象:mallocgcLarge

Since mcache and mcentral only manages spans of size class up to 32KB, large objects (greater than 32760 bytes) are allocated directly from mheap (see Span Allocation) without consulting mcache or mcentral. Spans accommodating large objects can be also either scan or noscan. Unlike small objects, large objects do not vary by span class: scan spans are always 0, and noscan spans are always 1.

mcache 和 mcentral 管理的大小类别最大为 32 KB。大对象(请求超过 32760 字节)直接从 mheap 分配(见分配 span),无须走 mcache 或 mcentral 的小对象缓存。容纳大对象的 span 同样分为 scan 和 noscan,但无须按大小再细分:scan 的 span 类别固定是 0,noscan 固定是 1。

When a large object is allocated, for example a slice with 1 million large structs, the kernel does not immediately commit physical memory. Instead, it reserves virtual address space for the allocation. Physical pages are only ever allocated when the program first writes to that region, thanks to demand paging.

分配大对象时,例如创建含一百万个大型结构体的切片,内核不会立即为整段地址配齐物理内存。它先预留虚拟地址空间,利用按需分页,等程序首次写入相应区域时才分配物理页。

Stack Management栈管理

As discussed in the Go Scheduler post, both Go runtime code and user code run on threads managed by the kernel. Each thread has its own stack—a contiguous block of memory that holds stack frames, which in turn store function parameters, local variables, and return addresses. Since allocating variables on the stack is simply adjusting the stack pointer (as explained in Stack Allocation), our focus is on how stacks are allocated and managed in Go.

如《Go 调度器》中所述,运行时代码和用户代码都运行在内核管理的线程上。每个线程有自己的栈:这是一块连续的内存区域,其中的栈帧保存函数参数、局部变量和返回地址。栈上分配局部变量只需调整栈指针(见栈上分配),这里着重讨论的是 Go 如何分配并管理栈本身。

In Go, a thread’s stack is called the system stack, while a goroutine’s stack is simply called the stack. To manage execution contexts, the runtime introduces the m (thread) and g (goroutine) abstractions. Every g has a stack field recording the start and end addresses of its stack. Each m has a special g0 goroutine, whose stack represents the system stack. The runtime uses g0 when performing operations that must run on the system stack rather than a goroutine stack, such as growing or shrinking a goroutine’s stack.

Go 把线程的栈称为系统栈,goroutine 的栈则简称为栈。运行时分别用 m(线程)和 g(goroutine)来管理执行上下文。每个 g 都有一个 stack 字段,记录栈的起止地址。每个 m 又有一个特殊的 goroutine g0,它使用的正是系统栈。对于必须在系统栈上运行的工作,比如扩展或收缩 goroutine 栈,运行时会切换到 g0。

The system stack of the main thread is allocated by the kernel when a Go process starts. For non-main threads, their stack are allocated by either the kernel or the Go runtime, depending on the operating system and whether CGO is used. On Darwin and Windows, the kernel always allocates the system stack for non-main threads. On Linux, however, the Go runtime allocates a system stack for non-main threads unless CGO is used.

Go 进程启动时,主线程的系统栈由内核分配。其他线程的系统栈可能由内核分配,也可能由 Go 运行时分配,取决于操作系统和是否使用 CGO。在 Darwin 和 Windows 上,非主线程的系统栈也一直由内核分配;在 Linux 上,不使用 CGO 时,Go 运行时会为非主线程分配系统栈。

Darwin 和 Windows 的进程虚拟内存布局
Virtual memory layout of processes in Darwin/Windows
Darwin 和 Windows 的进程虚拟内存布局
Linux 的进程虚拟内存布局
Virtual memory layout of processes in Linux
Linux 的进程虚拟内存布局

A system stack allocated by the kernel resides outside Go’s managed virtual memory space, while a system stack allocated by the runtime is created inside it. The kernel ensures that its system stacks do not collide with Go’s managed memory. Kernel-allocated system stacks typically range from 512 KB to several MB, whereas system stacks allocated by Go are fixed at 16 KB. By contrast, goroutine stacks start with 2 KB and can grow or shrink dynamically as needed.

内核分配的系统栈位于 Go 管理的虚拟内存区域之外,运行时自行分配的系统栈则位于其中。内核保证自己分配的系统栈不会与 Go 管理的内存冲突。内核分配的系统栈通常为 512 KB 到数 MB,Go 分配的系统栈则固定为 16 KB。相比之下,goroutine 的栈从 2 KB 起步,能按需增长或收缩。

Allocating Stack: stackalloc分配栈:stackalloc

Stacks managed by the Go runtime—whether system stacks or goroutine stacks—are accommodated in spans, just like heap objects. You can think of a stack as a special kind of heap object dedicated to holding local variables and function call frames during execution of Go runtime or user code.

无论是系统栈还是 goroutine 栈,只要由 Go 运行时管理,就和堆对象一样放在 span 中。可以把栈理解成一种特殊的堆内存,用于保存 Go 运行时或用户代码执行期间的局部变量与函数调用帧。

Stacks are normally allocated from the current P’s mcache. If garbage collection is in progress, when the number of processors P changes, or if the current thread is detached from its P during a system call, stacks are instead allocated from the global pools. There are two pools: small for stack smaller than 32 KB, or large pool for stacks equal to or bigger than 32 KB.

通常从当前 P 的 mcache 分配栈。在垃圾收集期间、处理器 P 的数量改变时,或当前线程因系统调用而与 P 分离时,可能需要绕过本地缓存,从全局池分配。全局池有两类:小栈池服务不足 32 KB 的栈,大栈池服务大于或等于 32 KB 的栈。

Goroutines starts wit small stack thus allocated by the small stack pool, but when it grows beyond 32 KB due to calling more functions or allocating more stack variables, the large stack pool is used instead. This behavior will be described in Stack Growth section.

goroutine 刚启动时栈很小,来自小栈池。随着函数调用加深或栈上变量增加,栈如果增长到 32 KB 或以上,就要使用大栈池。具体过程见栈增长。

Allocating Stack from Pool从全局池分配栈

The small stack pool is a four-entry array of doubly linked lists of mspan, each span holding metadata for a block of virtual memory. All spans in this pool belong to span class 0 and cover four contiguous pages, hence each span takes up 32 KB. Each entry in the array corresponds to a stack order, which determines stack size: order 0 → every stack is 2 KB, order 1 → every stack is 4 KB, order 2 → every stack is 8 KB, and order 3 → every stack is 16 KB.

小栈池是一个长度为 4 的数组,每项都是由 mspan 组成的双向链表。每个 span 的元数据描述一段虚拟内存;池中的 span 均属 span 类别 0,占四张连续页,即 32 KB。数组的每一项对应一个栈的阶数:0 阶为 2 KB,1 阶为 4 KB,2 阶为 8 KB,3 阶为 16 KB。

You might wonder why stacks are categorized into orders and sizes this way. The reason is that goroutine stacks are contiguous memory regions that double in size when they grow. This behavior will be explained in more detail in the Stack Growth section.

为什么这样划分阶数和大小?因为 goroutine 栈占用连续内存,每次增长都将容量扩大一倍。详见栈增长。

小栈池的组织方式
Pool of small stack
小栈池的组织方式

When a stack smaller than 32 KB is requested, the runtime first determines the appropriate order based on the requested size. It then checks the head of the linked list for that order to find an available span. If no span is available, it requests one from mheap (see Span Allocation) and splits it into stacks of the required order. Once a span is ready, Go runtime takes the first available stack, updates the span’s metadata, and returns the stack.

申请小于 32 KB 的栈时,运行时先按请求大小确定阶数,再检查相应链表的表头,看有没有可用 span。如果没有,就向 mheap 申请一个(见分配 span),并按该阶数将其切成多个栈。span 就绪后,取出第一个可用栈,更新元数据,再返回这个栈。

Large stack pool is as simple as a linked list of stack of various sizes, each stack contained within an mspan of span class 0. When a stack equal to or larger than 32 KB is requested, the first stack is popped from the linked list and returned. If the list is empty, it requests a new span from mheap (see Span Allocation).

大栈池的结构更简单,按大小保存空闲栈的链表,每个栈由一个 span 类别为 0 的 mspan 描述。申请大于或等于 32 KB 的栈时,从对应链表表头弹出一个栈返回。如果链表为空,就向 mheap 申请新的 span(见分配 span)。

Note that since stack pools are global, and can be accessed by multiple threads concurrently Therefore, they are protected by a mutex lock to ensure thread safety with the trade-off of lower throughput due to lock contention.

栈池是全局的,多个线程可以并发访问,所以需要用互斥锁保护。这样保证了线程安全,代价是发生锁争用时吞吐量会下降。

Allocating Stack from Cache从本地缓存分配栈

In order to reduce lock contention when allocating stack, each processor P maintains its owns stack cache in its mcache. Similar to small stack pool, the stack cache is a four-entry array of singly linked lists of free stacks, each entry corresponding to a stack order.

为减少栈分配时的锁争用,每个处理器 P 都在自己的 mcache 中维护栈缓存。它和小栈池一样有四个数组项,对应四种阶数;不同的是,每项保存一条由空闲栈组成的单向链表。

When serving a small stack allocation request, the runtime first checks the stack cache of the current P for an available stack. If none is available, it refills the cache by requests some stacks from the small stack pool, caches them, and return the first one. Large stacks aren’t served from the stack cache, they are always allocated from the large stack pool directly.

收到小栈请求,运行时先查当前 P 的缓存。如果没有可用栈,就从小栈池批量取一些放入缓存,并返回其中第一个。大栈不经过本地缓存,直接从全局大栈池分配。

Stack Growth: morestack栈增长:morestack

Segmented Stack分段栈

Historically, Go used a segmented stack approach. Each goroutine started with a small stack. If a function call required more stack space than available in the current stack, a new, another stack would be allocated and linked to the previous one. When the function returned, the new stack would be deallocated, and execution would continue on the previous stack. This process was known as a stack split.

早期 Go 使用分段栈。每个 goroutine 起初只有一个小栈。如果一次函数调用所需的栈空间超过当前栈剩余容量,运行时就分配一个新栈段,将它链接到上一段。函数返回后,新段被释放,执行回到原先的栈段。这个过程称为栈分裂(stack split)。

The below code snippet and figure illustrate a scenario where the ingest function process data from a file line by line, where stack frame of read scatters across two stacks. If the stack pointer reach some limit (the so-called stack guard, which will be discussed later), calls to read or process may trigger a stack split. Please note that goroutine stack may not consist of contiguous memory regions in this approach.

下面的代码和图展示了 ingest 逐行处理文件的场景,图中 read 的调用帧分布在两个栈段上。如果栈指针触及某个界限,也就是稍后会讲的栈保护边界,调用 read 或 process 就可能触发栈分裂。在这种方案中,一个 goroutine 使用的几段栈内存未必连续。

func ingest(path string) {
  ...
  for {
    line, err := read(file) // Causes stack split.
    if err == io.EOF {
      break
    }
    process(line)
  }
  ...
}
分段栈中的栈分裂
Stack split in segmented stack strategy
分段栈中的栈分裂

However, this segmented stack approach had a performance issue known as the hot stack split problem. If a function repeatedly need frequent allocation and deallocation of stacks within a tight loop, the entire process would incur a significant performance penalty. When the function returns, the newly allocated stack are deallocated. Since each stack split takes 60 nanosecond, the issue leads to significant overhead as it happens for every iteration of the loop.

这种方案有一个性能问题,叫作热栈分裂(hot stack split)。如果一个紧密循环反复调用某个恰好需要新栈段的函数,每次调用都会分配新段,返回时再释放。按一次栈分裂约耗时 60 纳秒计算,每轮迭代都来一次,累积的开销就很可观。

One trick to avoid this issue is to add padding to the stack frame of functions that are called frequently within loops. We can allocate dummy local variables to increase the stack frame size, thus reducing the likelihood of stack splits. But from the perspective of Go programmers, this is error-prone and reduces code readability.

一个应对办法是在循环中频繁调用的函数的栈帧里增加填充。通过声明不起实际作用的局部变量把栈帧撑大,可以降低反复触发栈分裂的概率。但这种写法易出错,也损害程序的可读性。

Contiguous Stack连续栈

To mitigate the hot stack split problem, Go after version 1.4 switches to an approach so-called contiguous stacks. When goroutine stack needs to grow, a new larger stack twice bigger than the current one is allocated. The content of the current stack is copied to the new stack, and the goroutine switches to use the new stack.

为缓解热栈分裂问题,Go 在 1.4 前后转向连续栈方案。goroutine 需要更大的栈时,运行时先分配一个容量为旧栈两倍的新栈,将原有内容复制过去,再让 goroutine 切换到新栈。

连续栈增长时的复制过程
Copy stack in contiguous stack strategy
连续栈增长时的复制过程

The figure above illustrates a contiguous stack and shows that it is not shrunk when underutilized (e.g., after the first iteration completes). This behavior helps mitigate the hot-split problem.

上图展示了连续栈。即使使用率暂时下降,例如第一次循环结束后,它也不会马上收缩。这样,下一轮就不必在同一处再次付出扩栈的代价。

If goroutine stacks were never shrunk, however, memory can be wasted if it grows significantly during peak usage but later leaves most of that space unused. In fact, with contiguous stack scheme, a goroutine stack is shrunk during a garbage collector cycle rather than when a function returns. If the total in-used stack size is less than a quarter of the current stack size, a new smaller stack half the size of the current one is allocated. Content of the current stack is copied to the new stack, and the goroutine switches to use the new stack. See shrinkstack for more details.

但如果栈永远不缩,峰值期间长大的栈在负载回落后就会浪费大量空间。连续栈方案把收缩安排在垃圾收集周期,而不是函数返回时。若已用空间不足当前栈大小的四分之一,就分配一个容量减半的新栈,把原有内容复制过去,并让 goroutine 使用新栈。细节见 shrinkstack。

As mentioned in the Go Scheduler post, in order for goroutine stack to grow, some checks must be inserted at function prologues. The check is basically CPU instruction and costs CPU cycles to execute. For small functions that are called frequently, this overhead can be significant. To mitigate this overhead, small functions are marked with //go:nosplit directive, which tells the compiler not to insert stack growth checks in their prologues.

如《Go 调度器》所述,为了让 goroutine 栈能按需增长,编译器会在函数序言中插入检查。检查要执行 CPU 指令,对频繁调用的小函数也可能有可观的成本。某些小函数会使用 //go:nosplit 指令,让编译器省略其函数序言中的扩栈检查。

⚠️ Don’t be confused. Split in //go:nosplit sounds relate to stack split in segmented stack approach, but it actually means stack growth check in contiguous stack approach as well.

⚠️ //go:nosplit 中的 split 容易让人联想到旧分段栈的“分裂”。在连续栈方案中,这个标记同样适用,此时它指的是跳过扩栈检查。

Stack Guard栈保护边界

When a function is called, the stack pointer is decreased by the size of the function’s stack frame. It is then checked against the goroutine’s stack guard, which determines whether stack growth is required. The stack guard consists of two parts: StackNosplitBase and StackSmall. On Linux, this places the guard at 928 bytes above the stack bottom—800 bytes for StackNosplitBase and 128 bytes for StackSmall.

函数调用需要为栈帧留出空间:把栈指针减去栈帧大小,再与 goroutine 的栈保护边界比较,以判断是否需要扩栈。保护区包括 StackNosplitBase 和 StackSmall 两部分。在文中讨论的 Linux 配置下,边界位于栈内存低地址端以上 928 字节处,其中 StackNosplitBase 为 800 字节,StackSmall 为 128 字节。

栈保护边界在 goroutine 栈中的位置
The position of stack guard in a goroutine stack
栈保护边界在 goroutine 栈中的位置

But overflow means that stack pointer goes beyond the stack, so why is the stack pointer checked against the stack guard rather than the bottom of the stack? The reasons are explained in this comment in the Go runtime source code. Let me re-explain them in simpler terms.

栈溢出意味着栈指针越过栈的实际边界,为什么检查的却是保护边界,而不是栈内存的起点?Go 运行时源码的这段注释给出了解释。下面换一种更直白的说法。

First, since Go allows functions not to perform stack grow checks by marking them with //go:nosplit, space equal to StackNosplitBase must be reserved so that they can execute safely without referencing any invalid address. For example, morestack—which itself handles stack growth—must have its entire stack frame fit within the allocated stack.

首先,Go 允许标记了 //go:nosplit 的函数省略扩栈检查,因此必须预留 StackNosplitBase 这么多空间,保证它们执行时不会访问无效地址。例如,负责扩栈的 morestack 自己的整个栈帧就必须能放进现有栈里。

Second, it serves as an optimization for small functions having stack frame smaller than StackSmall. When these functions are called, Go doesn’t bother decreasing the stack pointer and checking it against the stack guard. Instead, it simply checks whether the current stack pointer is below the stack guard, saving one CPU instruction per function call by skipping the stack pointer adjustment.

其次,这样可以优化栈帧小于 StackSmall 的函数。检查这些函数时,无须先把栈指针减去帧大小再比较,直接判断当前栈指针是否低于保护边界即可。每次调用的检查都能省下一条调整栈指针的指令。

Reusing Stack: stackfree复用栈:stackfree

When goroutine finishes its execution, goroutine stack is shrunk due to having too much available space, or system thread managed by Go runtime exits, their stacks are marked as reusable. If the goroutine is currently attached with a processor P and the size of P’s stack cache is small enough, its stack is returned to the stack cache of that P. Otherwise, the stack is returned to the global pool—either small stack pool with the corresponding order or large stack pool, depending on the size of the stack.

goroutine 执行结束、因空闲空间过多而换用较小的栈,或由运行时管理系统栈的线程退出时,旧栈就可以复用。如果当前线程关联着处理器 P,而 P 的栈缓存还足够小,栈会归还给这个 P 的缓存;否则按大小归还到全局池,即小栈池中相应阶数的链表,或大栈池。

When stack is returned to the global pool, the corresponding page of memory will be returned to kernel if garbage collection is not in progress. Check this comment in the Go runtime source code for more details.

栈归还到全局池后,若当前不在垃圾收集期间,相应内存页可以进入回收流程。具体何时释放以及为何要考虑 GC 状态,见运行时源码的注释。

Stack or Heap?栈还是堆?

One may think that var n T always allocates it on the stack, and new(T) or &T{} always allocates an object of type T on the heap. But that’s not always the case in Go. Let’s examine some hypothetical examples to get the problem behind and how Go addresses them.

直觉上,var n T 像是一定在栈上分配,而 new(T) 或 &T{} 像是一定在堆上分配 T。在 Go 中,实际结果并不由这几种写法决定。先用一个假设的例子看清问题,再看 Go 如何处理。

Consider the following program which defines a function getUserByID that retrieves a user their identifier. Hypothetically, getUserByID allocates a User struct on the stack, fetches user data from a database, and returns the address of that struct, aka. returning the pointer to that struct.

下面的程序定义了一个按 ID 读取用户的函数 getUserByID。先假设它在栈上分配 User 结构体,从数据库填入该用户的数据,再返回结构体的地址,也就是指向它的指针。

func getUserByID(id int64) *User {
  var user User
  user = db.FindUserByID(id)
  return &user
}

func main() {
  var userID int64 = 1
  var user *User = getUserByID(userID)
  var userAge = user.age
  user.age = userAge + 1
}
栈帧退出后可能产生的悬空指针
Dangling pointer problem
栈帧退出后可能产生的悬空指针

When getUserByID is called, the user variable is placed at address 0xe0 in its stack frame. After the function returns, user still holds the address 0xe0, but that address is no longer valid because the stack frame of getUserByID has been popped. When main then tries to access user.age, it dereferences an invalid address, leading to a dangling pointer problem and undefined behavior.

如图所示,假设调用 getUserByID 时,变量 user 位于其栈帧的 0xe0 地址。函数返回后,调用方拿到的指针值仍为 0xe0,但 getUserByID 的栈帧已经弹出,该地址不再能作为原来对象的有效地址。如果 main 再访问 user.age,就会解引用这个无效指针,产生悬空指针问题,行为也无法确定。

To prevent such issues, Go employs a technique called escape analysis, which happens during compile time. Escape analysis determines whether a variable—declared with var n T, new(T), &T{}, or make(T)—could be safely allocated on goroutine stack or must escape to the heap. If a variable is recognized to be referenced outside its declaring function, it is allocated on the heap to ensure it can be safely accessed after the function returns.

为避免这种情况,Go 在编译时进行逃逸分析。无论变量通过 var n T、new(T)、&T{} 还是 make(T) 创建,编译器都要判断:能安全放在 goroutine 的栈上,还是必须逃逸到堆上?如果变量在声明它的函数返回后仍有引用,编译器会将它放到堆上,保证之后的访问仍然有效。

In the above code snippet, the user variable is determined to escape to the heap because its address is returned and used in main. Therefore, the compiler allocates user on the heap to prevent dangling pointer issues.

在刚才的程序中,user 的地址被返回给 main 并在那里使用。编译器因此判定 user 逃逸,将它分配在堆上,避免图中假设的悬空指针。

Escape analysis also attempts to keep variables on the stack, even if they would normally be heap-allocated (e.g., those created with new(T), &T{}, or make(T) keywords), as long as they are proven to be used only within the function scope and do not take more memory space than MaxImplicitStackVarSize at compile time.

逃逸分析也会尽量把原来看起来需要堆分配的变量留在栈上,例如通过 new(T)、&T{} 或 make(T) 创建的变量。前提是编译器能证明它只在函数作用域内使用,并且编译时已知的空间需求不超过 MaxImplicitStackVarSize。

You can verify these behaviors by compiling the following program with the -gcflags="-m" option, which instructs the compiler to print optimization decisions, including escape analysis results.

可以给下面的程序加上 -gcflags="-m" 选项进行编译。编译器会输出所做的优化决策,其中就包括逃逸分析结果。

package main

type User struct { ID int64 }

func newUser(id int64) *User {
  user := User{ID: id}
  return &user
}

func main() {
  _ = newUser(20250603)
  _ = make([]User, 100)
}

// $ go build -gcflags="-m" main.go
// ./main.go:6:2: moved to heap: user
// ./main.go:12:10: make([]User, 100) does not escape

We can see that user is moved to the heap because it escapes, while the slice created by make([]User, 100) doesn’t escape because it’s used only in main and its size is less than MaxImplicitStackVarSize.

可以看到,user 因为逃逸而移到了堆上。用 make([]User, 100) 创建的切片只在 main 中使用,所需空间也小于 MaxImplicitStackVarSize,因此没有逃逸。

Now, try updating the length of the slice to 1,000,000 and compile the program again with the same option and observe the output below. user still escapes to the heap, but this time the slice created with make([]User, 1000000) also escapes because its size exceeds MaxImplicitStackVarSize, thus too large to fit on stack.

现在把切片长度改为 1,000,000,用同一选项重新编译,观察下面的输出。user 依然逃逸;这一次,make([]User, 1000000) 创建的底层存储也要到堆上分配,因为它超过 MaxImplicitStackVarSize,太大而不适合放在栈上。

// $ go build -gcflags="-m" main.go
// ./main.go:6:2: moved to heap: user
// ./main.go:12:10: make([]User, 1000000) escapes to heap

Case Studies案例分析

As you have a better understanding of how Go allocates memory for heap objects and stacks, let’s examine some real-world examples to understand how Go allocates memory in practice and how to optimize heap allocations.

了解了堆对象和栈的分配机制,下面看几个真实场景,观察这些机制在程序里产生的效果,以及如何减少堆分配。

Case Study 1: Reusing Underlying Array of Slice案例一:复用切片的底层数组

As you may know that a slice in Go is a descriptor containing a pointer to an underlying array, its length, and its capacity. When we create a new slice with make([]T, length, capacity), the compiler overwrites the make keyword with a call to makeslice in the Go runtime. makeslice then calls mallocgc with the size equal to capacity*sizeof(T) to allocate the underlying array on the heap. In other words, capacity tracks the size of the underlying array, while length tracks the number of in-use elements in the array.

Go 的切片是一个描述符,包含指向底层数组的指针、长度和容量。用 make([]T, length, capacity) 创建切片时,编译器可以将 make 转换成对运行时 makeslice 的调用。makeslice 再调用 mallocgc,以 capacity*sizeof(T) 的大小为底层数组分配堆内存。换句话说,capacity 记录底层数组能容纳多少个元素,length 记录当前使用了多少个。

append appends new elements to the end of the slice, increasing its length. If the new length exceeds the current capacity, append calls mallocgc to allocate a new underlying array twice as big, copies the existing elements to the new array, and updates the slice descriptor to point to the new array.

append 把新元素追加到切片末尾,同时增加长度。如果新长度超过当前容量,就需要调用 mallocgc 分配更大的底层数组,将已有元素复制过去,并更新切片描述符指向新数组。原文在下例中以容量翻倍来估算。

A slice in Go can be resliced using the [start:end] syntax. Reslicing creates a new slice header that points to a subrange of elements within the same underlying array as the original slice. Importantly, this operation does not copy the data or allocate additional memory—the new slice simply reuses the existing array. See more at Slice Intro.

用 [start:end] 可以对 Go 切片重新切片。这会生成一个新的切片头,指向原底层数组中的一段范围。它不会复制元素,也无须另行分配底层存储;新切片复用原数组。详见《Go 切片:用法与内部机制》。

We can leverage the reslicing behavior to optimize heap allocations by reusing the underlying array of a slice instead of creating a new one. Consider the following program that parses a CSV file processes each row one by one, where each row can have a large number of fields.

可以利用这一点减少堆分配:把已有切片的底层数组留给下一次使用。下面这个程序逐行解析和处理 CSV 文件,每行都可能有很多字段。

package main

import (
  "bufio"
  "os"
)

func parse(line string) []string {
  start := 0
  var row []string
  for i := 0; i < len(line); i++ {
    if line[i] == ',' {
      row = append(row, line[start:i])
      start = i + 1
    }
  }
  row = append(row, line[start:])
  return row
}

func process(row []string) {
  // Process the line.
}

func main() {
  file, _ := os.Open("input.csv")
  defer file.Close()

  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    line := scanner.Text()
    row := parse(line)
    process(row)
  }
}

Since parse creates an empty slice for each line, it allocates a new underlying array on the heap every time it is called. Plus, since append is called for each field in the line, it may trigger multiple heap allocations if the number of fields exceeds the initial capacity of the underlying array. The same path in mallocgc is executed repeatedly, leading to many wasteful heap allocations.

parse 每次解析新行都从空切片开始,所以每次调用都要在堆上分配新的底层数组。每读到一个字段还要执行 append,一旦容量不够,同一行就可能发生多次分配。程序会一次次走过 mallocgc 的同一条路径,重复做许多本可以省掉的分配。

Let’s optimize the program by reusing the underlying array of the row slice. By reslicing with row[:0], we reset the length of the slice to zero while keeping its capacity unchanged. Heap allocations only occur in the first call to parse, i.e. when the first line is parsed. For a CSV file having 1,024 fields and 1,000,000 lines, the number of heap allocations is reduced from 1000000*log₂(1024)=10⁷ to just log₂(1024)=10 simply by reslicing.

现在让 row 切片复用底层数组。row[:0] 将长度重置为零,同时保留容量。这样,对字段数相同的各行来说,只需在首次调用 parse、解析首行时为 row 扩容。原文按 1024 个字段、一百万行以及容量翻倍估算,底层数组的堆分配次数可以从 1000000*log₂(1024)=10⁷ 降至 log₂(1024)=10,改动只是重新切片。

package main

import (
  "bufio"
  "os"
)

func parse(line string, row []string) []string {
  start := 0
  for i := 0; i < len(line); i++ {
    if line[i] == ',' {
      row = append(row, line[start:i])
      start = i + 1
    }
  }
  row = append(row, line[start:])
  return row
}

func process(row []string) {
  // Process the line.
}

func main() {
  file, _ := os.Open("input.csv")
  defer file.Close()

  var row []string
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    line := scanner.Text()
    row = row[:0] // Reuse the underlying array.
    row = parse(line, row)
    process(row)
  }
}

Case Study 2: Grouping Multiple Variables into a Single Struct案例二:把多个变量合并到一个结构体

Recently, there was a commit in the iter package that grouped multiple scalar variables into a single struct.

iter 包中有一次提交,把多个标量变量合并到了一个结构体里。

将多个变量声明合并为一个结构体声明的改动
Change that groups multiple variable declarations into one struct declaration
将多个变量声明合并为一个结构体声明的改动

Originally, since these 7 variables outlive the function scope, all of them are allocated on the heap separately, thus results in 7 calls to mallocgc. Although some of these variables are smaller than 16 bytes and can be allocated by the Tiny Objects Allocator, the overhead of 7 calls to mallocgc is still significant if Pull is called frequently.

之前这 7 个变量的生命周期都超出了函数作用域,因此分别在堆上分配,共调用 7 次 mallocgc。即便其中一些变量小于 16 字节,可以由微小对象分配器处理,但 Pull 一旦频繁执行,这 7 次 mallocgc 调用仍是一笔不小的开销。

By grouping these variables into a single struct, only one call to mallocgc is needed to allocate the struct on the heap, improving memory allocation efficiency. This approaches has a downside, however, that it couples unrelated objects together, which prevents the garbage collector from reclaiming individual objects that are no longer needed. However, in this specific case, since most of these variables are used together, the trade-off is acceptable.

将它们放在同一个结构体中,只需调用一次 mallocgc,就能在堆上为整个结构体分配空间。这也有代价:本来互不相关的对象被绑在一起,即使其中某个已不再使用,也不能单独被垃圾收集器回收。不过在这个例子里,大部分变量原本就会一起使用,所以这项取舍可以接受。

The benchmark results in the original PR (copied below) show that the number of heap allocations is reduced from 11 to 5. The difference matches the above analysis, where 7 variables are grouped into a single struct, thus saving 6 calls to mallocgc. Also, the memory consumption and allocation time are reduced by around one-third.

原始 PR 给出的基准测试结果如下。堆分配从每次操作 11 次减少到 5 次,差值与上述分析一致:7 个变量合成一个结构体,正好省掉 6 次 mallocgc 调用。每次操作的内存用量和耗时也都下降了约三分之一。

         │ /tmp/bench.old │           /tmp/bench.new           │
         │     sec/op     │   sec/op     vs base               │
Pull-12       218.6n ± 7%   146.1n ± 0%  -33.19% (p=0.000 n=10)

         │ /tmp/bench.old │           /tmp/bench.new           │
         │      B/op      │    B/op     vs base                │
Pull-12        288.0 ± 0%   176.0 ± 0%  -38.89% (p=0.000 n=10)

         │ /tmp/bench.old │           /tmp/bench.new           │
         │   allocs/op    │ allocs/op   vs base                │
Pull-12       11.000 ± 0%   5.000 ± 0%  -54.55% (p=0.000 n=10)

Case Study 3: Reusing Objects with sync.Pool案例三:用 sync.Pool 复用对象

In some applications, many short-lived, stateless objects of the same type are created and discarded frequently. A typical example is the pp printer object, which is used extensively throughout the fmt package to format strings in commonly used functions, such as Fprintf and Sprintf.

有些应用会反复创建和丢弃大量相同类型、寿命短暂且不需要保留状态的对象。典型例子是 fmt 包广泛使用的 pp 打印器。常用的 Fprintf 和 Sprintf 都靠它格式化字符串。

If these functions allocated a new pp object, used it to perform formatting, and then throws it away then when your application writes 10,000 logs per second, translating into 10,000 pp objects being allocated and later scanned by the garbage collector every second. This pattern leads to significant overhead due to frequent heap allocations and garbage collection.

假如这些函数每次都创建一个新的 pp,完成格式化就将它丢弃,那么当应用每秒写一万条日志时,每秒就要分配一万个 pp 对象,之后还要由垃圾收集器处理。频繁的堆分配和垃圾收集将带来明显开销。

To reduce this overhead, Go provides sync.Pool, a mechanism for caching and reusing objects of the same type. When handling a Get request, sync.Pool first looks for an available object in its pool. If none is found, it invokes a user-defined New function to create one, which ultimately calls mallocgc to allocate it on the heap. Once the client is done with the object, it can be returned to the pool using the Put method. By recycling objects, sync.Pool reduces both the number of heap allocations and the number of objects the garbage collector needs to scan, thereby improving performance.

为减少这类开销,Go 提供了 sync.Pool 来缓存和复用同类型对象。收到 Get 请求时,sync.Pool 先寻找池中可用的对象。如果没有,可以调用用户定义的 New 函数创建一个对象,最终由 mallocgc 在堆上分配。用完后,调用方可以通过 Put 将对象放回池中。通过复用对象,sync.Pool 同时减少了堆分配和需要 GC 扫描的对象,从而提高性能。

In reality, Fprintf and Sprintf requests a pp from the pool, uses it for formatting, and then returns it to the pool for future reuse. The ppFree pool is initialized when the fmt package is imported.

实际上,Fprintf 和 Sprintf 会从池中取出一个 pp,完成格式化后再归还,供之后复用。ppFree 池在导入 fmt 包时完成初始化。

sync.Pool is designed to be lock-free and efficient under high concurrency. To achieve this, it relies on a technique called pinning, which prevents a goroutine from being preempted while getting or putting an object in the pool. Since a sync.Pool is local to each processor P, pinning ensures that the goroutine remains on the same P during the operation.

sync.Pool 的设计目标是在高并发下高效运行,常用的本地路径无须加锁。它使用固定到处理器(pinning)的机制,在获取或归还对象的关键区间阻止当前 goroutine 被抢占。sync.Pool 为各个处理器 P 维护本地存储;固定期间,goroutine 会留在同一个 P 上,直到操作完成。

Conclusion结语

Go’s memory allocator is designed with a clear goal in mind: to provide efficient in highly concurrent applications. By layering its allocation strategy across mheap, mcentral, and mcache, the runtime balances global coordination with per-P caching, minimizing lock contention while keeping allocations fast. Stacks, though managed differently from heap objects, follow similar principles of efficient allocation and adaptive growth.

Go 内存分配器的设计目标,是在高并发程序中高效分配内存。把工作分层交给 mheap、mcentral 和 mcache 后,运行时可以兼顾全局协调与各 P 的本地缓存,减少锁争用,同时保持分配速度。栈的管理方式与堆对象不同,但也体现了按需分配和自适应增长的思路。

For most Go developers, these details remain hidden behind simple constructs such as &T{}, new(T), and make(T). Yet, understanding the internals provides valuable insight into why certain patterns perform better than others, how the garbage collector interacts with allocation, and what trade-offs the runtime makes to achieve low-latency concurrency at scale. As you build and optimize Go applications, keep in mind that every variable or goroutine you create is ultimately backed by these mechanisms.

对大多数 Go 开发者来说,&T{}、new(T) 和 make(T) 已经把这些机制藏到了简单的语法后面。了解底层实现,有助于解释为什么某种写法更快、垃圾收集器如何与分配器配合,以及运行时为了在大规模并发下保持低延迟做了哪些取舍。编写和优化程序时可以记住:我们创建的每个变量、每个 goroutine,最终都由这些机制支撑。

I hope you find this knowledge useful for writing more efficient and reliable Go programs. If you have any concerns, feel free to leave a comment. If you really enjoyed my content, please consider Buy Me A Coffee ! 😄

希望这些内容能帮助你写出更高效、更可靠的 Go 程序。有疑问欢迎到原文留言。如果你喜欢这篇文章,也欢迎请我喝杯咖啡!😄

References参考文献


Edit page
Share this post:

Comments


Previous Post
Agent Harnesses Need Their eBPF|智能体运行框架也需要自己的 eBPF
Next Post
Enjoy Every Sandwich|享受每一个三明治