Gold, an experimental Go local docs server, Go docs generation tool, and code reader. NEW!

-- show type implemention relations --

-- show code statistics --

-- smooth code view experiences --

-- and more... --

Memory Blocks

Go is a language which supports automatic memory management, such as automatic memory allocation and automatic garbage collection. So Go programmers can do programming without handling the underlying verbose memory management. This not only brings much convenience and saves Go programmers lots of time, but also helps Go programmers avoid many careless bugs.

Although knowing the underlying memory management implementation details is not necessary for Go programmers to write Go code, understanding some concepts and being aware of some facts in the memory management implementation by the standard Go compiler and runtime is very helpful for Go programmers to write high quality Go code.

This article will explain some concepts and list some facts of the implementation of memory block allocation and garbage collection by the standard Go compiler and runtime. Other aspects, such as memory apply and memory release in memory management, will not be touched in this article.

Memory Blocks

A memory block is a continuous memory segment to host value parts at run time. Different memory blocks may have different sizes, to host different value parts. One memory block may host multiple value parts at the same time, but each value part can only be hosted within one memory block, no matter how large the size of that value part is. In other words, for any value part, it never crosses memory blocks.

a struct value often have several fields. So when a memory block is allocated for a struct value, the memory block will also host (the direct parts of) these field values.

an array values often have many elements. So when a memory block is allocated for a array value, the memory block will also host (the direct parts of) the array element values.

the underlying element sequences of two slices may be hosted on the same memory block, the two element sequences even can overlap with each other. There are many reasons when one memory block may host multiple value parts. Some of them:

A Value References the Memory Blocks Which Host Its Value Parts

We have known that a value part can reference another value part. Here, we extend the reference definition by saying a memory block is referenced by all the value parts it hosts. So if a value part v is referenced by another value part, then the other value will also reference the memory block hosting v , indirectly.

When Will Memory Blocks Be Allocated?

explicitly call the new and make built-in functions. A new call will always allocate exact one memory block. A make call will allocate more than one memory blocks to host the direct part and underlying part(s) of the created slice, map or channel value.

and built-in functions. A call will always allocate exact one memory block. A call will allocate more than one memory blocks to host the direct part and underlying part(s) of the created slice, map or channel value. create maps, slices and anonymous functions with corresponding literals. More than one memory blocks may be allocated in each of the processes.

declare variables.

assign non-interface values to interface values (when the non-interface value is not a pointer value).

concatenate non-constant strings.

convert strings to byte or rune slices, and vice versa, except some special compiler optimization cases.

convert integers to strings.

call the built-in append function (when the capacity of the base slice is not large enough).

function (when the capacity of the base slice is not large enough). add a new key-element entry pair into a map (when the underlying hash table needs to be resized). In Go, memory blocks may be allocated but not limited at following situations:

Where Will Memory Blocks Be Allocated On?

For every Go program compiled by the official standard Go compiler, at run time, each goroutine will maintain a stack, which is a memory segment. It acts as a memory pool for some memory blocks to be allocated from/on. The initial stack size of each goroutine is small (about 2k bytes on 64-bit systems). The stack size will grow and shrink as needed in goroutine running.

(Please note, for the standard Go compiler, there is a limit of stack size each goroutine can have. For standard Go compiler 1.11, the default maximum stack size is 1 GB on 64-bit systems, and 250 MB on 32-bit systems. We can call the SetMaxStack function in the runtime/debug standard package to change the size.)

Memory blocks can be allocated on stacks. Memory blocks allocated on the stack of a goroutine can only be used (referenced) in the goroutine internally. They are goroutine localized resources. They are not safe to be referenced crossing goroutines. A goroutine can access or modify the value parts hosted on a memory block allocated on the stack of the goroutine without using any data synchronization techniques.

Heap is a singleton in each program. It is a virtual concept. If a memory block is not allocated on any goroutine stack, then we say the memory block is allocated on heap. Value parts hosted on memory blocks allocated on heap can be used by multiple goroutines. In other words, they can be used concurrently. Their uses should be synchronized when needed.

Heap is a conservative place to allocate memory blocks on. If compilers detect a memory block will be referenced crossing goroutines or can't easily confirm whether or not the memory block is safe to be put on the stack of a goroutine, then the memory block will be allocated on heap at run time. This means some values can be safely allocated on stacks may be also allocated on heap.

allocating memory blocks on stacks is much faster than on heap.

memory blocks allocated on a stack don't need to be garbage collected.

stack memory blocks are more CPU cache friendly than heap ones. In fact, stacks are not essential for Go programs. Go compiler/runtime can allocate all memory block on heap. Supporting stacks is just to make Go programs run more efficiently:

If a memory block is allocated somewhere, we can also say the value parts hosted on the memory block are allocated on the same place.

If some value parts of a local variable declared in a function is allocated on heap, we can say the value parts (and the variable) escape to heap. By using Go Toolchain, we can run go build -gcflags -m to check which local values (value parts) will escape to heap at run time. As mentioned above, the current escape analyzer in the standard Go compiler is still not perfect, many local value parts can be allocated on stacks safely will still escape to heap.

An active value part allocated on heap still in use must be referenced by at least one value part allocated on a stack. If a value escaping to heap is a declared local variable, and assume its type is T , Go runtime will create (a memory block for) an implicit pointer of type *T on the stack of the current goroutine. The value of the pointer stores the address of the memory block allocated for the variable on heap (a.k.a., the address of the local variable of type T ). Go compiler will also replace all uses of the variable with the dereferences of the pointer value at compile time. The *T pointer value on stack may be marked as dead since a later time, so the reference relation from it to the T value on heap will disappear. The reference relation from the *T value on stack to the T value on heap plays an important role in the garbage collection process which will be described below.

Similarly, we can view each package-level variable is allocated on heap, and the variable is referenced by an implicit pointer which is allocated on a global memory zone. In fact, the implicit pointer references the direct part of the package-level variable, and the direct part of the variable references some other value parts.

A memory block allocated on heap may be referenced by multiple value parts allocated on different stacks at the same time.

if a field of a struct value escapes to heap, then the whole struct value will also escape to heap.

if an element of an array value escapes to heap, then the whole array value will also escape to heap.

if an element of a slice value escapes to heap, then all the elements of the slice will also escape to heap.

if a value (part) v is referenced by a value (part) which escapes to heap, then the value (part) v will also escape to heap. Some facts:

A memory block created by calling new function may be allocated on heap or stacks. This is different to C++.

When the size of a goroutine stack changes, a new memory segment will be allocated for the stack. So the memory blocks allocated on the stack will very likely be moved, or their addresses will change. Consequently, the pointers, which must be also allocated on the stack, referencing these memory blocks also need to be modified accordingly.

When Can a Memory Block Be Collected?

Memory blocks allocated for direct parts of package-level variables will never be collected.

The stack of a goroutine will be collected as a whole when the goroutine exits. So there is no need to collect the memory blocks allocated on stacks, individually, one by one. Stacks are not collected by the garbage collector.

For a memory block allocated on heap, it can be safely collected only if it is no longer referenced (either directly or indirectly) by all the value parts allocated on goroutine stacks and the global memory zone. We call such memory blocks as unused memory blocks. Unused memory blocks on heap will be collected by the garbage collector.

package main var p *int func main() { done := make(chan bool) // "done" will be used in main and the following // new goroutine, so it will be allocated on heap. go func() { x, y, z := 123, 456, 789 _ = z // z can be allocated on stack safely. p = &x // For x and y are both ever referenced p = &y // by the global p, so they will be both // allocated on heap. // Now, x is not referenced by anyone, so // its memory block can be collected now. p = nil // Now, y is als not referenced by anyone, // so its memory block can be collected now. done Here is an example to show when some memory blocks can be collected: Sometimes, smart compilers, such as the standard Go compiler, may make some optimizations so that some references are removed earlier than we expect. Here is such an example. package main import "fmt" func main() { // Assume the length of the slice is so large // that its elements must be allocated on heap. bs := make([]byte, 1 << 31) // A smart compiler can detect that the // underlying part of the slice bs will never be // used later, so that the underlying part of the // slice bs can be garbage collected safely now. fmt.Println(len(bs)) } Sometimes, smart compilers, such as the standard Go compiler, may make some optimizations so that some references are removed earlier than we expect. Here is such an example. Please read value parts to learn the internal structures of slice values. By the way, sometimes, we may hope the slice bs is guaranteed to not being garbage collected until fmt.Println is called, then we can use a runtime.KeepAlive function call to tell garbage collectors that the slice bs and the value parts referenced by it are still in use. For example, package main import "fmt" import "runtime" func main() { bs := make([]int, 1000000) fmt.Println(len(bs)) // A runtime.KeepAlive(bs) call is also // okay for this specified example. runtime.KeepAlive(&bs) } For example, runtime.KeepAlive function calls are often needed if unsafe pointers are involved.

How Are Unused Memory Blocks Detected?

The current standard Go compiler (version 1.15) uses a concurrent, tri-color, mark-sweep garbage collector. Here this article will only make a simple explanation for the algorithm. A garbage collection (GC) process is divided into two phases, the mark phase and the sweep phase. In the mark phase, the collector (a group of goroutines actually) uses the tri-color algorithm to analyze which memory blocks are unused. The following quote is token from objects is either value parts or memory blocks. At the start of a GC cycle all objects are white. The GC visits all roots, which are objects directly accessible by the application such as globals and things on the stack, and colors these grey. The GC then chooses a grey object, blackens it, and then scans it for pointers to other objects. When this scan finds a pointer to a white object, it turns that object grey. This process repeats until there are no more grey objects. At this point, white objects are known to be unreachable and can be reused. The following quote is token from a Go blog article , in which anis either value parts or memory blocks. About why the algorithm uses three colors instead of two colors, please search "write barrier golang" for details. Here only provides two references: eliminate STW stack re-scanning and mbarrier.go. In the sweep phase, the marked unused memory blocks will be collected. The GC algorithm is a non-compacting one, so it will not move memory blocks to rearrange them.

When Will an Unused Memory Block Be Collected?

The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. Unused heap memory blocks are viewed as garbage by Go runtime and will be collected to reuse or release memory. The garbage collector is not always running. It will start when a threshold is satisfied. So an unused memory block may be not collected immediately when it becomes unused. Instead, it will be collected eventually. Currently (Go Toolchain 1.15), the threshold is controlled by GOGC environment variable The value of this environment variable determines the frequency of garbage collecting, and it can be modified at run time by calling runtime/debug.SetGCPercent function. Smaller values lead to more frequent garbage collections. A negative percentage disables automatical garbage collection. A garbage collection process can also be started manually by calling the runtime.GC function. One more thing needs to note is, for the current official Go runtime (v1.15), a new garbage collection process will start automatically if garbage collection has not run for two minutes. The gargage collection strategies might change in later official Go runtime versions. An unused memory block may not be released to OS immediately after it is collected, so that it can be reused for new some value parts. Don't worry, the official Go runtime is much less memory greedy than most Java runtimes.