Skip to content
Middle+69 views

Как работает сборщик мусора в Go, и каковы его последствия для производительности приложения?

Practice

Asked at

AI answer

In Go, the garbage collector automatically frees the memory of objects that are no longer reachable by the program. Its primary mechanism is concurrent, tracing mark-and-sweep: the GC finds roots (stack variables and global references), marks reachable objects, and then frees the unmarked ones. Most of this work runs in parallel with the application; short stop-the-world phases are needed, among other things, to switch between stages. A write barrier helps track references correctly while the program and collector run concurrently.

The GC reduces the risk of leaks caused by forgotten deallocations, but it comes at a cost: it uses CPU, temporarily increases memory consumption, and can add latency. Frequent object allocations, especially of short-lived objects, usually increase GC workload. GOGC controls the trade-off between heap growth and collection frequency, while GOMEMLIMIT lets you set a memory target for the runtime. Tune them based on measurements: profile allocations and latency rather than disabling the GC without a compelling reason.