CodeBlanks Logo Icon CodeBlanks

Summary - GC

Combine tri-color and GOGC to write a memory analysis.

GC summary

Go's GC is a concurrent, tri-color, mark-and-sweep collector. The program keeps running between two short STWs, and the write barrier keeps things correct. The tuning knobs are GOGC (how often) and GOMEMLIMIT (how much); the measurement tools are gctrace, ReadMemStats and the heap profile.

But the biggest win comes from changing the code: fewer and shorter-lived heap allocations.

Measure, then tune

A typical investigation: use gctrace=1 to see what percentage of CPU the GC takes; if it's high, find the lines that allocate most with the alloc_space heap profile; fix them; fine-tune with GOGC/GOMEMLIMIT only as a last step. Changing the settings first hides the problem instead of solving it.

Practice Allocation comparison

Compare two functions with testing.AllocsPerRun: one starts each call with make([]int, 0) and appends 100 items, the other starts with capacity via make([]int, 0, 100). Print the capacity version's allocation count (1) and whether it is less than the other.

Starter code

main.go
package main

import (
    "fmt"
    "testing"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "testing"
)

var sink []int

func main() {
    a := testing.AllocsPerRun(10, func() {
        s := make([]int, 0)
        for i := 0; i < 100; i++ {
            s = append(s, i)
        }
        sink = s
    })
    b := testing.AllocsPerRun(10, func() {
        s := make([]int, 0, 100)
        for i := 0; i < 100; i++ {
            s = append(s, i)
        }
        sink = s
    })
    fmt.Println(b, b < a)
}

Expected output

1 true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Does Go's GC move objects in memory (compaction)?

  • No; Go's GC doesn't move objects and limits fragmentation with size classes Correct answer
  • Yes, every cycle
  • Only large objects
  • Only with GOGC=off

Explanation: Go uses a non-moving GC; the allocator keeps fragmentation low by placing objects in pages by size class.

2 Memory limit

Question
debug.____(900 << 20)  // ~900 MiB
Answer
debug.SetMemoryLimit(900 << 20)  // ~900 MiB

Explanation: SetMemoryLimit is the in-code counterpart of GOMEMLIMIT.

3 Group summary

Term Meaning
Tri-color Marking algorithm
Write barrier Concurrent correctness
GOGC GC frequency
sync.Pool Reduces allocation

All lessons in Expert