How does garbage collection work in Golang?
Aug 01, 2025 am 07:10 AMGo's garbage collection (GC) is automatic, using a concurrent three-color mark removal algorithm, implements concurrent collection through a write barrier, optimizes short-life cycle object recycling, and maintains low pause time. Developers can improve performance through object reuse and avoids memory leaks. 1. GC marks accessible objects from the root object and clears unreachable objects. 2. Write barriers ensure that reference updates are not missed during concurrency. 3. Although there is no explicit generational division, it is optimized according to "most objects die prematurely", and short-cycle GC is frequently executed. 4. Only submillisecond pauses are generated at the beginning and end of the mark to ensure low latency. 5. Developers can use sync.Pool to reuse objects to reduce allocation pressure and avoid memory problems caused by long-term holding of large objects or global references. Go's GC runs efficiently in the background, balancing memory and CPU overhead, and is suitable for modern applications.
Garbage collection (GC) in Go is automatic and designed to simplify memory management for developers. Unlike languages like C or C , where you manually allocate and free memory, Go handles this for you by reclaiming memory that's no longer in use. Here's how it works in a practical, real-world sense.

1. Tracing Garbage Collector (Mark-and-Sweep)
Go uses a concurrent, tri-color mark-and-sweep garbage collector. This means it traces through your program's memory, starting from "root" objects (like global variables and stack variables), and marks everything that's still reachable. Anything not marked is considered garbage and gets cleaned up.
The process has two main phases:

- Mark phase : The GC walks through all reachable objects and marks them as "in use."
- Sweep phase : It goes through unmarked memory regions and reclaims them for future allocations.
Because it's concurrent , the garbage collector runs alongside your program (the "mutator"), minimizing pauses. This is a big deal for low-latency applications.
2. Write Barriers Enable Concurrent Collection
One key to making GC concurrent is the use of write barriers . When your program updates a pointer (eg, obj.field = newObj
), a small piece of code (the write barrier) runs first to inform the GC about the change.

This ensures the GC doesn't miss references created while it's running. Without write barriers, the GC might incorrectly collect an object that was just referenced. They add a tiny overhead but allow the program to keep running without stopping for long GC pauses.
3. General Assumptions (Not Explicit, But Optimized)
Go doesn't have a traditional generational GC like Java (with young/old generations), but it's optimized around the same idea: most objects die young .
The Go GC focuses on efficiency by:
- Prioritizing fast allocation (using a bump allocator in thread-local caches).
- Running frequently, short GC cycles to clean up short-lived objects quickly.
- Tuning GC frequency based on heap growth (controlled via
GOGC
).
GOGC=100
means GC runs when heap memory doubles. You can adjust this to trade memory for CPU usage.
4. Low Pause Times via Concurrency
Modern Go GC is optimized for low-latency . Most of the marking happens while your program runs. Only brief stop-the-world (STW) pauses occur:
- At the start of marking (to set up the process).
- At the end (to finalize marking).
These pauses are typically in the sub-millisecond range, making Go suitable for latency-sensitive services.
Tips for Developers
Even though GC is automatic, you can influence performance:
- Avoid holding references to large objects longer than needed.
- Reuse objects via pools (
sync.Pool
) for high-frequency allocations. - Be mindful of memory leaks from global slices/maps or goroutines holding references.
// Example: sync.Pool to reduce allocation pressure var bufferPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } buf := bufferPool.Get().(*bytes.Buffer) // use buf bufferPool.Put(buf)
Basically, Go's GC works quietly in the background, using smart concurrency and tracing to keep your app running smoothly with minimal pauses. It's not magic, but it's well-tuned for modern applications.
The above is the detailed content of How does garbage collection work in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
