How Go Decides When to Garbage Collect

The Formula

Here’s the formula that the GC uses to figure out what size heap you need:

next_gc=live_heap×(1+GOGC100)\text{next\_gc} = \text{live\_heap} \times (1 + \frac{\text{GOGC}}{100})

For example, if the actual memory in use after the garbage collector has done its job is 82MB, that means:

  • Live heap: 82 MB (actual memory in use after GC).

  • GOGC: 100 (default value, meaning 100%).

  • Calculation: 82 MB×(1+100100)=82 MB×2=164 MB82 \text{ MB} \times (1 + \frac{100}{100}) = 82 \text{ MB} \times 2 = \textbf{164 MB}

The slight difference might occur due to rounding and internal GC accounting.

This means that the GC won’t run again until the heap grows to ~164 MB. This is Go’s way of balancing:

  • Memory usage: Don’t let the heap grow unbounded.

  • CPU efficiency: Don’t run GC too frequently (wastes CPU).

Tuning GOGC

You can adjust this behaviour with the GOGC environment variable:

  • GOGC=100 (default): Next GC at 2× live heap.

  • GOGC=200: Next GC at 3× live heap (less frequent GC, more memory).

  • GOGC=50: Next GC at 1.5× live heap (more frequent GC, less memory).

  • GOGC=off: Disable automatic GC entirely (not recommended for production).

Knowledge Check
If your live heap is 100 MB after a GC cycle and GOGC is set to its default value of 100, at what heap size will the garbage collector run next?
100 MB
150 MB
200 MB
Correct! 🎉 `GOGC=100` means the heap is allowed to grow by 100% of the live heap size. So 100 MB + (100 MB * 1.0) = 200 MB!
Not quite. The correct answer is C. The default `GOGC` of 100 sets the target heap size to 2x the live heap size.
What is the effect of lowering the GOGC environment variable to 50?
It physically restricts the application from using more than 50% of the server's RAM.
The GC will run more frequently (at 1.5x live heap), saving memory but spending more CPU time on garbage collection.
It limits the GC to only run a maximum of 50 times per second.
Correct! 🎉 Tuning `GOGC` is a direct CPU vs Memory tradeoff. Lowering it saves memory but forces the CPU to spend more time running GC cycles.
Not quite. The correct answer is B. Lowering `GOGC` reduces the heap growth multiplier, causing GC cycles to trigger earlier and more often.

Quiz Complete!

You scored 0 out of 2.

Comments

© 2025 Threads of Thought. Built with Astro.