Stack vs Heap, Garbage Collection, and pprof
Understanding how Go manages memory is crucial for performance optimization.
go build -gcflags="-m" reveals this.1. Save this code as main.go.
2. Run go build -gcflags="-m" main.go to see escape analysis output.
3. Run go run main.go and visit http://localhost:6060/debug/pprof/ to explore the profiler.
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"time"
)
// leakyFunc simulates a memory leak by appending to a global slice
var leak []int
func leakyFunc() {
for {
// Append 1MB of data every second
leak = append(leak, make([]int, 1024*128)...)
time.Sleep(time.Second)
}
}
func main() {
// Start pprof server
go func() {
log.Println("Starting pprof server on :6060")
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
fmt.Println("Running... Check pprof at http://localhost:6060/debug/pprof/")
leakyFunc()
}
Answer: When the compiler cannot prove that the variable is not referenced after the function returns. Common cases: returning a pointer to a local variable, passing a variable to `fmt.Println` (which takes `interface{}`), or if the variable is too large for the stack.
Answer: It's a non-generational, concurrent, tri-color mark-and-sweep collector. 1. Mark: Traverses pointers starting from roots (stack, globals) to find live objects (colors them black). 2. Sweep: Reclaims memory from white (unreachable) objects. It uses a "Pacer" to determine when to trigger the next GC cycle to maintain a target heap size ratio (GOGC).
Answer: They are not guaranteed to run promptly (or at all if the program exits). They delay memory reclamation because the object must survive one GC cycle to be finalized, and another to be freed. Avoid them for critical resource cleanup; use `defer` instead.
Answer: Processor. It represents a resource required to execute Go code and holds a local run queue of Goroutines (Gs).