A Guide to the Go Garbage Collector
小结:
1、
stack allocation
he space is stored on the goroutine stack.
escape to the heap
the Go compiler cannot determine its lifetime
垃圾回收目标:堆空间大小始终低于目标的堆空间大小。
The GC's goal is to finish a collection cycle before the total heap size exceeds the target heap size.
内存限制
Memory limit
Until Go 1.19, GOGC was the sole parameter that could be used to modify the GC's behavior. While it works great as a way to set a trade-off, it doesn't take into account that available memory is finite. Consider what happens when there's a transient spike in the live heap size: because the GC will pick a total heap size proportional to that live heap size, GOGC must be configured such for the peak live heap size, even if in the usual case a higher GOGC value provides a better trade-off.
The visualization below demonstrates this transient heap spike situation.
1.19 支持设置运行时内存限制
OOM 内存溢出
If the example workload is running in a container with a bit over 60 MiB of memory available, then GOGC can't be increased beyond 100, even though the rest of the GC cycles have the available memory to make use of that extra memory. Furthermore, in some applications, these transient peaks can be rare and hard to predict, leading to occasional, unavoidable, and potentially costly out-of-memory conditions.
That's why in the 1.19 release, Go added support for setting a runtime memory limit. The memory limit may be configured either via the GOMEMLIMIT
environment variable which all Go programs recognize, or through the SetMemoryLimit
function available in the runtime/debug
package.
This memory limit sets a maximum on the total amount of memory that the Go runtime can use.
Note: the target heap size is just a target, and there are several reasons why the GC cycle might not finish right at that target. For one, a large enough heap allocation can simply exceed the target. However, other reasons appear in GC implementations that go beyond the GC model this guide has been using thus far. For some more detail, see the latency section, but the complete details may be found in the additional resources.
reducing GC frequency may also lead to latency improvements
https://go.dev/doc/gc-guide