Performance, Profiling & Testing·Q369·Medium
Importing net/http/pprof for its side effect registers handlers under /debug/pprof/ on http.DefaultServeMux . The gotcha: if your public API server also uses…
Performance, Profiling & Testing·Q370·Medium
The CPU profiler is a sampling profiler: the runtime asks the OS for a timer signal (SIGPROF on Unix) at 100 Hz by default, and on each tick records the stack of the…
Performance, Profiling & Testing·Q371·Medium
The heap profile records allocation sites, sampled on average once per runtime.MemProfileRate bytes (default 512 KiB). It offers four sample types: inuse_space /…
Performance, Profiling & Testing·Q372·Medium
Symptom: runtime.NumGoroutine() (export it as a metric) grows monotonically along with memory. Diagnose with the goroutine profile: curl -s…
Performance, Profiling & Testing·Q373·Hard
Both are disabled by default because they add overhead. Block profile : where goroutines waited on synchronization primitives — channel send/recv, select , sync.Mutex ,…
Performance, Profiling & Testing·Q374·Hard
pprof aggregates samples into "where is time spent"; the execution tracer records a timeline of events : goroutine create/start/block/unblock, syscalls, network poller…
Performance, Profiling & Testing·Q375·Medium
b.Loop() returns true while the benchmark should keep iterating. It fixes three classic b.N mistakes: Setup cost : the timer is reset on the first call, so expensive…
Performance, Profiling & Testing·Q376·Hard
func square(x int) int { return x * x } func BenchmarkSquare(b *testing.B) { for i := 0; i < b.N; i++ { square(42) } } It typically reports something like 0.25 ns/op —…
Performance, Profiling & Testing·Q377·Medium
b.ReportAllocs() (or the -benchmem flag for all benchmarks) adds B/op and allocs/op columns. Allocations are often the best predictor of real-world cost because they…
Performance, Profiling & Testing·Q378·Medium
func TestParseDuration(t *testing.T) { tests := []struct { name string in string want time.Duration wantErr bool }{ {name: "seconds", in: "5s", want: 5 * time.Second},…
Performance, Profiling & Testing·Q379·Hard
func TestOrder(t *testing.T) { defer fmt.Println("defer") t.Cleanup(func() { fmt.Println("cleanup") }) for i := range 2 { t.Run(fmt.Sprint(i), func(t *testing.T) {…
Performance, Profiling & Testing·Q380·Medium
Parallel tests in a package run concurrently up to -parallel (default GOMAXPROCS ). Packages themselves run in parallel as separate processes ( -p ). Top-level parallel…
Performance, Profiling & Testing·Q381·Medium
defer : fine in a test without parallel subtests; runs when the function returns. t.Cleanup(fn) : runs after the test and all its subtests complete, in LIFO order.…
Performance, Profiling & Testing·Q382·Hard
Since Go 1.18, func FuzzXxx(f *testing.F) defines a coverage-guided fuzz target. f.Add supplies seed inputs; f.Fuzz takes a function whose first parameter is *testing.T…
Performance, Profiling & Testing·Q383·Hard
Testing code with timeouts, tickers, and background goroutines usually means real sleeps (slow and flaky) or injecting a fake clock everywhere. testing/synctest…
Performance, Profiling & Testing·Q384·Medium
Go's implicit interface satisfaction lets the consumer define a small interface describing only what it needs; production code passes the real type, tests pass a…
Performance, Profiling & Testing·Q385·Medium
Handlers : call the handler directly with httptest.NewRequest and httptest.NewRecorder — no network, fast. Clients : spin up httptest.NewServer (real loopback listener)…
Performance, Profiling & Testing·Q386·Medium
The toolchain rewrites source to increment counters per basic block. go test -coverprofile=cover.out ./... go tool cover -func=cover.out # per-function percentages go…
Performance, Profiling & Testing·Q387·Hard
PGO (GA in Go 1.21) feeds a CPU profile from production into the compiler so it optimizes hot paths more aggressively. The Go team reports typical gains of 2–14% CPU.…
Performance, Profiling & Testing·Q388·Hard
The compiler inlines functions whose body cost is under a budget (~ 80 AST nodes ). Inlining removes call overhead, but the bigger win is that it enables further…
Performance, Profiling & Testing·Q389·Hard
type Point struct{ X, Y int } func a() Point { p := Point{1, 2}; return p } // (1) func b() *Point { p := Point{1, 2}; return &p } // (2) func c() int { p := &Point{1,…
Performance, Profiling & Testing·Q390·Hard
Go is memory safe: every s[i] gets a runtime check that panics if i is out of range. The SSA backend's prove pass removes checks it can prove redundant. In tight loops…
Performance, Profiling & Testing·Q391·Hard
sync.Pool is a per-P cache of reusable temporary objects that reduces allocation rate and GC pressure for hot, short-lived objects (buffers, encoders). Semantics you…
Performance, Profiling & Testing·Q392·Medium
Strings are immutable, so s += x in a loop allocates a new string and copies everything each iteration: O(n²) bytes copied and n allocations. func concatPlus(parts…
Performance, Profiling & Testing·Q393·Hard
package main import ( "fmt" "strings" ) func main() { var a strings.Builder a.WriteString("hello") b := a b.WriteString(" world") fmt.Println(b.String()) } It panics :…
Performance, Profiling & Testing·Q394·Hard
Go's GC is a concurrent, non-generational, non-moving mark-sweep collector. Pacing: GOGC (default 100): the next GC triggers when the heap grows by GOGC% over the live…
Performance, Profiling & Testing·Q395·Medium
func main() { s := make([]int, 0, 2) a := append(s, 1) b := append(s, 2) fmt.Println(a[0], b[0], len(s), cap(s)) var grow []int prev := -1 for i := range 2000 { grow =…
Performance, Profiling & Testing·Q396·Hard
CPUs cache memory in 64-byte lines (128 on some ARM). If two cores write to different variables on the same cache line, the line ping-pongs between cores via the…
Performance, Profiling & Testing·Q397·Medium
Each field is aligned to its type's alignment (int64/pointers: 8 on 64-bit), and the struct's size is rounded up to its largest alignment. Poor ordering inserts padding.…
Performance, Profiling & Testing·Q398·Hard
A normal string(b) or []byte(s) copies because strings must be immutable. The compiler already avoids the copy in several cases: Map lookups: m[string(b)] (lookup only,…
Performance, Profiling & Testing·Q399·Medium
go test -race / go build -race instruments every memory access and uses ThreadSanitizer's happens-before (vector clock) algorithm. It reports when two goroutines access…
Performance, Profiling & Testing·Q400·Medium
Options for gating slow tests: testing.Short() : skip under go test -short . Build constraints: //go:build integration at the top of the file; run with go test…
Performance, Profiling & Testing·Q401·Medium
Functions named ExampleXxx in _test.go files serve as both documentation (rendered on pkg.go.dev next to the identifier) and tests. If the function ends with an //…
Performance, Profiling & Testing·Q402·Hard
A structured answer matters more than any one tool: Correlate metrics : CPU, RSS, goroutine count, GC cycles/sec and GC CPU fraction ( runtime/metrics ), request rate,…
Performance, Profiling & Testing·Q403·Hard
Benchmarks show allocs/op, but nobody reads benchmark output on every PR. For code that must stay allocation-free (encoders, loggers, request routing), lock it in with a…
Performance, Profiling & Testing·Q404·Hard
b.RunParallel(body) starts GOMAXPROCS × SetParallelism(p) goroutines (p defaults to 1) and splits the b.N iterations among them; each goroutine loops on pb.Next() . The…
Performance, Profiling & Testing·Q405·Hard
The old map was an array of buckets holding 8 entries each, with overflow buckets chained on collisions and incremental evacuation into a doubled array on growth. Go…
Performance, Profiling & Testing·Q406·Hard
The mark phase must scan every live object that contains pointers . Objects whose type has no pointers are allocated in "noscan" spans and are never scanned. So GC CPU…