-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance.html
More file actions
655 lines (569 loc) · 32 KB
/
Copy pathperformance.html
File metadata and controls
655 lines (569 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Go Performance | Ultimate Handbook</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="hero">
<h1>Go <span>Performance</span></h1>
<p>Stack vs heap, escape analysis, pprof profiling, sync.Pool, goroutine leaks, and writing efficient Go.</p>
<div class="hero-pills">
<span>Stack vs heap</span>
<span>Escape analysis</span>
<span>pprof</span>
<span>sync.Pool</span>
<span>Inlining</span>
<span>allocs/op</span>
<span>Goroutine leaks</span>
<span>strings.Builder</span>
</div>
</div>
<div class="layout has-toc">
<nav class="pkg-nav">
<a href="index.html" class="home-link">Go Handbook</a>
<div class="nav-group">Language</div>
<ul class="pkg-list">
<li><a href="basics.html"><span class="pkg-icon">📖</span>Basics</a></li>
<li><a href="data-structures.html"><span class="pkg-icon">📦</span>Data Structures</a></li>
<li><a href="concurrency.html"><span class="pkg-icon">🔀</span>Concurrency</a></li>
<li><a href="testing.html"><span class="pkg-icon">🧪</span>Testing</a></li>
<li><a href="reflection.html"><span class="pkg-icon">🔬</span>Reflection</a></li>
<li><a href="file-data.html"><span class="pkg-icon">📁</span>File & Data</a></li>
<li><a href="web.html"><span class="pkg-icon">🌐</span>Web</a></li>
<li><a href="packages-modules.html"><span class="pkg-icon">🗃</span>Packages & Modules</a></li>
<li><a href="performance.html" class="active"><span class="pkg-icon">⚡</span>Performance</a></li>
<li><a href="gotchas.html"><span class="pkg-icon">⚠️</span>Gotchas</a></li>
</ul>
<div class="nav-group">Packages</div>
<ul class="pkg-list">
<li><a href="strings-package-guide.html"><span class="pkg-icon">🔤</span>strings</a></li>
<li><a href="fmt-package-guide.html"><span class="pkg-icon">🖨</span>fmt</a></li>
<li><a href="strconv-package-guide.html"><span class="pkg-icon">🔢</span>strconv</a></li>
<li><a href="sort-package-guide.html"><span class="pkg-icon">📊</span>sort</a></li>
<li><a href="slices-package-guide.html"><span class="pkg-icon">🗂</span>slices</a></li>
<li><a href="io-package-guide.html"><span class="pkg-icon">🔌</span>io</a></li>
<li><a href="os-package-guide.html"><span class="pkg-icon">💻</span>os</a></li>
<li><a href="errors-package-guide.html"><span class="pkg-icon">⚠️</span>errors</a></li>
<li><a href="context-package-guide.html"><span class="pkg-icon">🎯</span>context</a></li>
<li><a href="time-package-guide.html"><span class="pkg-icon">⏱</span>time</a></li>
<li><a href="math-package-guide.html"><span class="pkg-icon">🧮</span>math</a></li>
</ul>
</nav>
<main class="content">
<!-- ── 1. STACK VS HEAP ──────────────────────────────────────── -->
<section class="section" id="stack-heap">
<div class="section-header">
<div class="section-icon icon-blue">🏗️</div>
<h2>Stack vs Heap</h2>
<span class="section-tag">allocation · escape analysis · GC</span>
</div>
<div class="diagram">
<pre> Stack Heap
────────────────────── ──────────────────────────────
Per-goroutine (starts at 8KB) Shared across all goroutines
Grows/shrinks automatically Managed by the GC
Fast: bump pointer allocation Slower: GC must scan and collect
Freed when function returns Freed when no more references
Rule: if a value's lifetime is bounded to a function call → stack
if it escapes (returned, sent to channel, stored) → heap</pre>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">What causes heap allocation</span>
<span class="card-badge badge-blue">Escape</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Returning a pointer: value escapes to heap</span>
<span class="kw">func</span> <span class="fn">newUser</span>() *<span class="typ">User</span> {
u := <span class="typ">User</span>{Name: <span class="str">"Alice"</span>} <span class="cmt">// u escapes</span>
<span class="kw">return</span> &u
}
<span class="cmt">// Storing in interface: concrete type escapes</span>
<span class="kw">var</span> i <span class="kw">any</span> = <span class="typ">User</span>{} <span class="cmt">// User escapes to heap</span>
<span class="cmt">// Sending pointer on channel: escapes</span>
ch <- &<span class="typ">User</span>{}
<span class="cmt">// Closure capturing a variable: escapes</span>
x := <span class="num">42</span>
f := <span class="kw">func</span>() { <span class="pkg">fmt</span>.<span class="fn">Println</span>(x) } <span class="cmt">// x escapes</span>
_ = f</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Escape analysis: see the decisions</span>
<span class="card-badge badge-blue">-gcflags</span>
</div>
<div class="code-wrap">
<pre><span class="cmt"># Show escape analysis decisions</span>
go build -gcflags="-m" ./...
<span class="cmt"># More verbose (shows why)</span>
go build -gcflags="-m=2" ./...
<span class="cmt">// Sample output:</span>
<span class="cmt">// ./main.go:8:2: &u escapes to heap</span>
<span class="cmt">// ./main.go:12:14: x escapes to heap</span>
<span class="cmt">// ./main.go:5:17: User{} does not escape</span>
<span class="cmt"># Disable inlining to see more escape detail</span>
go build -gcflags="-m -l" ./...</pre>
</div>
</div>
</div>
</section>
<!-- ── 2. PPROF ──────────────────────────────────────────────── -->
<section class="section" id="pprof">
<div class="section-header">
<div class="section-icon icon-gold">🔬</div>
<h2>pprof Profiling</h2>
<span class="section-tag">CPU · memory · goroutine · go tool pprof</span>
</div>
<div class="callout">
<span class="callout-icon">ℹ️</span>
<div>Profile before you optimize. pprof tells you exactly where CPU time and memory are spent: without it, optimizations are guesswork. Always benchmark before and after a change to confirm impact.</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">HTTP pprof endpoint: always-on profiling</span>
<span class="card-badge badge-gold">net/http/pprof</span>
</div>
<div class="code-wrap">
<pre><span class="kw">import</span> _ <span class="str">"net/http/pprof"</span> <span class="cmt">// registers /debug/pprof/ routes</span>
<span class="kw">func</span> <span class="fn">main</span>() {
<span class="cmt">// Expose on a separate port (never on your public port)</span>
<span class="kw">go</span> <span class="pkg">http</span>.<span class="fn">ListenAndServe</span>(<span class="str">":6060"</span>, <span class="kw">nil</span>)
<span class="cmt">// ... start your actual server</span>
}
<span class="cmt"># Capture 30s CPU profile</span>
go tool pprof http://localhost:<span class="num">6060</span>/debug/pprof/profile?seconds=30
<span class="cmt"># Heap profile</span>
go tool pprof http://localhost:<span class="num">6060</span>/debug/pprof/heap
<span class="cmt"># Goroutine dump</span>
go tool pprof http://localhost:<span class="num">6060</span>/debug/pprof/goroutine
<span class="cmt"># Open interactive web UI</span>
go tool pprof -http=:8081 cpu.prof</pre>
</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">Programmatic profiling</span>
<span class="card-badge badge-gold">runtime/pprof</span>
</div>
<div class="code-wrap">
<pre><span class="kw">import</span> <span class="str">"runtime/pprof"</span>
<span class="cmt">// CPU profile</span>
f, _ := <span class="pkg">os</span>.<span class="fn">Create</span>(<span class="str">"cpu.prof"</span>)
<span class="pkg">pprof</span>.<span class="fn">StartCPUProfile</span>(f)
<span class="kw">defer</span> <span class="pkg">pprof</span>.<span class="fn">StopCPUProfile</span>()
<span class="cmt">// Heap profile (call after workload)</span>
mf, _ := <span class="pkg">os</span>.<span class="fn">Create</span>(<span class="str">"mem.prof"</span>)
<span class="pkg">runtime</span>.<span class="fn">GC</span>() <span class="cmt">// run GC for accurate stats</span>
<span class="pkg">pprof</span>.<span class="fn">WriteHeapProfile</span>(mf)
mf.<span class="fn">Close</span>()</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Benchmark + pprof</span>
<span class="card-badge badge-gold">-cpuprofile</span>
</div>
<div class="code-wrap">
<pre><span class="cmt"># Run benchmark and produce profiles in one step</span>
go test -bench=BenchmarkFoo \
-cpuprofile=cpu.prof \
-memprofile=mem.prof \
./...
<span class="cmt"># Analyze the CPU profile</span>
go tool pprof cpu.prof
<span class="cmt"># Inside pprof REPL:</span>
<span class="cmt"># top10 : top 10 functions by self time</span>
<span class="cmt"># list Foo : annotated source for function Foo</span>
<span class="cmt"># web : open flame graph in browser</span></pre>
</div>
</div>
</div>
</section>
<!-- ── 3. REDUCING ALLOCATIONS ──────────────────────────────── -->
<section class="section" id="allocations">
<div class="section-header">
<div class="section-icon icon-green">♻️</div>
<h2>Reducing Allocations</h2>
<span class="section-tag">sync.Pool · strings.Builder · pre-alloc</span>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">sync.Pool: reuse temporary objects</span>
<span class="card-badge badge-green">sync.Pool</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Pool holds temporary objects to reduce GC pressure</span>
<span class="cmt">// Objects may be evicted at any time: never store state in them</span>
<span class="kw">var</span> bufPool = <span class="pkg">sync</span>.<span class="typ">Pool</span>{
New: <span class="kw">func</span>() <span class="kw">any</span> {
<span class="kw">return</span> <span class="fn">new</span>(<span class="pkg">bytes</span>.<span class="typ">Buffer</span>)
},
}
<span class="kw">func</span> <span class="fn">buildResponse</span>(data []<span class="typ">byte</span>) []<span class="typ">byte</span> {
buf := bufPool.<span class="fn">Get</span>().(*<span class="pkg">bytes</span>.<span class="typ">Buffer</span>)
buf.<span class="fn">Reset</span>() <span class="cmt">// always reset before use</span>
<span class="kw">defer</span> bufPool.<span class="fn">Put</span>(buf)
buf.<span class="fn">Write</span>(data)
<span class="kw">return</span> buf.<span class="fn">Bytes</span>()
}
<span class="cmt">// Before sync.Pool: N allocs/op (one Buffer per call)</span>
<span class="cmt">// After sync.Pool: ~0 allocs/op (Buffer is reused)</span></pre>
</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">strings.Builder: build strings without allocs</span>
<span class="card-badge badge-green">strings.Builder</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Concatenating with + allocates on every iteration</span>
<span class="kw">var</span> s <span class="typ">string</span>
<span class="kw">for</span> _, w := <span class="kw">range</span> words {
s += w <span class="cmt">// O(n²) allocations</span>
}
<span class="cmt">// strings.Builder: single allocation at the end</span>
<span class="kw">var</span> sb <span class="pkg">strings</span>.<span class="typ">Builder</span>
sb.<span class="fn">Grow</span>(<span class="fn">len</span>(words) * <span class="num">8</span>) <span class="cmt">// hint capacity if known</span>
<span class="kw">for</span> _, w := <span class="kw">range</span> words {
sb.<span class="fn">WriteString</span>(w)
}
result := sb.<span class="fn">String</span>()</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Pre-allocate slices and maps</span>
<span class="card-badge badge-green">make with cap</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Without pre-alloc: grows 2x repeatedly, many allocs</span>
<span class="kw">var</span> results []<span class="typ">int</span>
<span class="kw">for</span> i := <span class="kw">range</span> items {
results = <span class="fn">append</span>(results, <span class="fn">process</span>(items[i]))
}
<span class="cmt">// With pre-alloc: zero reallocations</span>
results = <span class="fn">make</span>([]<span class="typ">int</span>, <span class="num">0</span>, <span class="fn">len</span>(items))
<span class="kw">for</span> i := <span class="kw">range</span> items {
results = <span class="fn">append</span>(results, <span class="fn">process</span>(items[i]))
}
<span class="cmt">// Pre-alloc map</span>
m := <span class="fn">make</span>(<span class="kw">map</span>[<span class="typ">string</span>]<span class="typ">int</span>, <span class="fn">len</span>(keys))
<span class="kw">for</span> _, k := <span class="kw">range</span> keys {
m[k]++
}</pre>
</div>
</div>
</div>
</section>
<!-- ── 4. INLINING ───────────────────────────────────────────── -->
<section class="section" id="inlining">
<div class="section-header">
<div class="section-icon icon-purple">⚡</div>
<h2>Inlining</h2>
<span class="section-tag">-gcflags · inline budget · noinline</span>
</div>
<div class="callout">
<span class="callout-icon">ℹ️</span>
<div>The Go compiler inlines small functions at their call sites, eliminating the function call overhead and enabling further optimizations. A function is inlineable if its AST node count is within the inline budget (~80 nodes). Closures, <code>recover()</code>, and large functions are not inlined.</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">Check what gets inlined</span>
<span class="card-badge badge-purple">-gcflags -m</span>
</div>
<div class="code-wrap">
<pre><span class="cmt"># -m shows inlining decisions alongside escape analysis</span>
go build -gcflags="-m" ./...
<span class="cmt">// Output examples:</span>
<span class="cmt">// ./math.go:5:6: can inline Add</span>
<span class="cmt">// ./math.go:12:6: cannot inline Process: function too complex</span>
<span class="cmt">// ./main.go:20:12: inlining call to Add</span></pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Writing inlineable functions</span>
<span class="card-badge badge-purple">Small functions</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Inlineable: simple, small, no recover</span>
<span class="kw">func</span> <span class="fn">max</span>(a, b <span class="typ">int</span>) <span class="typ">int</span> {
<span class="kw">if</span> a > b { <span class="kw">return</span> a }
<span class="kw">return</span> b
}
<span class="cmt">// Not inlineable: too complex, or uses recover</span>
<span class="kw">func</span> <span class="fn">safeDiv</span>(a, b <span class="typ">int</span>) (result <span class="typ">int</span>) {
<span class="kw">defer</span> <span class="kw">func</span>() {
<span class="kw">if</span> r := <span class="fn">recover</span>(); r != <span class="kw">nil</span> { result = <span class="num">0</span> }
}()
<span class="kw">return</span> a / b
}
<span class="cmt">// Force no inlining (useful for benchmarks)</span>
<span class="cmt">//go:noinline</span>
<span class="kw">func</span> <span class="fn">doWork</span>() {}</pre>
</div>
</div>
</div>
</section>
<!-- ── 5. GOROUTINE LEAKS ────────────────────────────────────── -->
<section class="section" id="goroutine-leaks">
<div class="section-header">
<div class="section-icon icon-red">🚰</div>
<h2>Goroutine Leaks</h2>
<span class="section-tag">blocked goroutines · goleak · runtime</span>
</div>
<div class="callout warn">
<span class="callout-icon">⚠️</span>
<div>A leaked goroutine is one that is blocked indefinitely: waiting on a channel that will never be written to, or a mutex that will never be released. Leaked goroutines consume memory and OS resources forever. In servers, leaks compound over time and cause OOM crashes.</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Common leak patterns and fixes</span>
<span class="card-badge badge-red">Leak patterns</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// ✗ LEAK: goroutine blocks on send if nobody reads</span>
ch := <span class="fn">make</span>(<span class="kw">chan</span> <span class="typ">int</span>) <span class="cmt">// unbuffered</span>
<span class="kw">go func</span>() {
result := <span class="fn">doWork</span>()
ch <- result <span class="cmt">// blocks forever if caller already returned</span>
}()
<span class="kw">return</span> <span class="cmt">// goroutine is now leaked</span>
<span class="cmt">// ✓ FIX: buffered channel or context cancellation</span>
ch := <span class="fn">make</span>(<span class="kw">chan</span> <span class="typ">int</span>, <span class="num">1</span>) <span class="cmt">// buffered: send never blocks</span>
<span class="cmt">// ✓ FIX: use context to stop the goroutine</span>
<span class="kw">go func</span>() {
<span class="kw">select</span> {
<span class="kw">case</span> ch <- <span class="fn">doWork</span>():
<span class="kw">case</span> <-ctx.<span class="fn">Done</span>(): <span class="cmt">// exits if context is cancelled</span>
}
}()</pre>
</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">Detect leaks in tests with goleak</span>
<span class="card-badge badge-red">goleak</span>
</div>
<div class="code-wrap">
<pre><span class="kw">import</span> <span class="str">"go.uber.org/goleak"</span>
<span class="kw">func</span> <span class="fn">TestMain</span>(m *<span class="pkg">testing</span>.<span class="typ">M</span>) {
<span class="pkg">goleak</span>.<span class="fn">VerifyTestMain</span>(m)
}
<span class="cmt">// Or per test:</span>
<span class="kw">func</span> <span class="fn">TestWorker</span>(t *<span class="pkg">testing</span>.<span class="typ">T</span>) {
<span class="kw">defer</span> <span class="pkg">goleak</span>.<span class="fn">VerifyNone</span>(t)
<span class="cmt">// test code here</span>
<span class="cmt">// goleak.VerifyNone fails if any goroutine leaked</span>
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Count goroutines at runtime</span>
<span class="card-badge badge-red">runtime</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Quick check: current goroutine count</span>
before := <span class="pkg">runtime</span>.<span class="fn">NumGoroutine</span>()
<span class="fn">doSomething</span>()
after := <span class="pkg">runtime</span>.<span class="fn">NumGoroutine</span>()
<span class="kw">if</span> after > before {
t.<span class="fn">Errorf</span>(<span class="str">"goroutine leak: before=%d after=%d"</span>, before, after)
}
<span class="cmt">// pprof goroutine profile shows stack traces</span>
<span class="cmt">// of all live goroutines: useful to identify what's blocked</span></pre>
</div>
</div>
</div>
</section>
<!-- ── 6. MEMORY EFFICIENCY ──────────────────────────────────── -->
<section class="section" id="memory">
<div class="section-header">
<div class="section-icon icon-gold">🧠</div>
<h2>Memory Efficiency</h2>
<span class="section-tag">struct layout · value types · GC pressure</span>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">Struct field ordering: reduce padding</span>
<span class="card-badge badge-gold">Alignment</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Bad: compiler inserts 7 bytes of padding</span>
<span class="kw">type</span> <span class="typ">Bad</span> <span class="kw">struct</span> {
a <span class="typ">bool</span> <span class="cmt">// 1 byte</span>
<span class="cmt">// 7 bytes padding</span>
b <span class="typ">int64</span> <span class="cmt">// 8 bytes</span>
c <span class="typ">bool</span> <span class="cmt">// 1 byte</span>
<span class="cmt">// 7 bytes padding</span>
} <span class="cmt">// total: 24 bytes</span>
<span class="cmt">// Good: largest fields first</span>
<span class="kw">type</span> <span class="typ">Good</span> <span class="kw">struct</span> {
b <span class="typ">int64</span> <span class="cmt">// 8 bytes</span>
a <span class="typ">bool</span> <span class="cmt">// 1 byte</span>
c <span class="typ">bool</span> <span class="cmt">// 1 byte</span>
<span class="cmt">// 6 bytes padding</span>
} <span class="cmt">// total: 16 bytes</span>
<span class="cmt">// Check size: unsafe.Sizeof(Bad{}) → 24</span></pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Value types vs pointer types</span>
<span class="card-badge badge-gold">Values</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Prefer values for small structs (≤ ~3 words)</span>
<span class="cmt">// Copying is cheaper than a pointer dereference</span>
<span class="kw">type</span> <span class="typ">Point</span> <span class="kw">struct</span>{ X, Y <span class="typ">float64</span> }
<span class="kw">func</span> <span class="fn">distance</span>(p <span class="typ">Point</span>) <span class="typ">float64</span> { ... } <span class="cmt">// value: stays on stack</span>
<span class="cmt">// Use pointers for large structs to avoid copying</span>
<span class="kw">type</span> <span class="typ">Config</span> <span class="kw">struct</span>{ ... } <span class="cmt">// 100+ fields</span>
<span class="kw">func</span> <span class="fn">process</span>(c *<span class="typ">Config</span>) { ... } <span class="cmt">// pointer: single 8-byte copy</span>
<span class="cmt">// Slice of values vs slice of pointers:</span>
[]<span class="typ">Point</span> <span class="cmt">// contiguous memory: cache friendly</span>
[]*<span class="typ">Point</span> <span class="cmt">// scattered heap objects: more GC work</span></pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Avoiding fmt.Sprintf for hot paths</span>
<span class="card-badge badge-gold">Allocations</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// fmt.Sprintf always allocates (uses reflection internally)</span>
msg := <span class="pkg">fmt</span>.<span class="fn">Sprintf</span>(<span class="str">"user %d not found"</span>, id) <span class="cmt">// alloc</span>
<span class="cmt">// strconv is allocation-free for numeric conversions</span>
<span class="kw">var</span> buf [<span class="num">32</span>]<span class="typ">byte</span>
b := <span class="pkg">strconv</span>.<span class="fn">AppendInt</span>(buf[:<span class="num">0</span>], <span class="typ">int64</span>(id), <span class="num">10</span>) <span class="cmt">// no alloc</span>
<span class="cmt">// errors.New creates a constant error: safe to reuse</span>
<span class="kw">var</span> <span class="typ">ErrNotFound</span> = <span class="pkg">errors</span>.<span class="fn">New</span>(<span class="str">"not found"</span>)
<span class="cmt">// Return ErrNotFound instead of fmt.Errorf("not found") in hot paths</span>
<span class="cmt">// Only use fmt.Errorf (with %w) when wrapping with context at boundaries</span></pre>
</div>
</div>
</section>
<!-- ── 7. READING BENCHMARK OUTPUT ──────────────────────────── -->
<section class="section" id="benchmarks">
<div class="section-header">
<div class="section-icon icon-blue">📊</div>
<h2>Reading Benchmark Output</h2>
<span class="section-tag">ns/op · B/op · allocs/op · benchstat</span>
</div>
<div class="diagram">
<pre> go test -bench=. -benchmem ./...
BenchmarkEncode-8 1234567 42.3 ns/op 64 B/op 1 allocs/op
│ │ │ │ │ └── heap allocations per op
│ │ │ │ └──────────── bytes allocated per op
│ │ │ └─────────────────────────── wall time per operation
│ │ └────────────────────────────────────── iterations run
│ └─────────────────────────────────────────── GOMAXPROCS (CPU count)
└─────────────────────────────────────────────────────────── benchmark name</pre>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">benchstat: compare two runs</span>
<span class="card-badge badge-blue">benchstat</span>
</div>
<div class="code-wrap">
<pre><span class="cmt"># Install</span>
go install golang.org/x/perf/cmd/benchstat@latest
<span class="cmt"># Run before and after, save output</span>
go test -bench=. -count=5 ./... > before.txt
<span class="cmt"># (make your change)</span>
go test -bench=. -count=5 ./... > after.txt
<span class="cmt"># Compare</span>
benchstat before.txt after.txt
<span class="cmt"># Output shows % change and p-value:</span>
<span class="cmt"># BenchmarkFoo 42.3ns ± 2% 31.1ns ± 1% -26.5% (p=0.008)</span></pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">What to look for</span>
<span class="card-badge badge-blue">Interpretation</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// High allocs/op → look for heap escapes,</span>
<span class="cmt">// string concatenation, interface conversions</span>
<span class="cmt">// High B/op with low allocs/op → large objects,</span>
<span class="cmt">// consider pooling or in-place updates</span>
<span class="cmt">// High ns/op with 0 allocs → CPU-bound;</span>
<span class="cmt">// profile with -cpuprofile to find hot spots</span>
<span class="cmt">// Noisy results (wide ± range) → run with -count=10,</span>
<span class="cmt">// close background apps, use benchstat for stats</span>
<span class="cmt">// Always measure the whole system; microbenchmarks</span>
<span class="cmt">// can be misleading if the hot path is elsewhere</span></pre>
</div>
</div>
</div>
</section>
<!-- ── 99. QUICK REFERENCE ───────────────────────────────────── -->
<section class="section" id="reference">
<div class="section-header">
<div class="section-icon icon-blue">📋</div>
<h2>Quick Reference</h2>
<span class="section-tag">Cheat-sheet</span>
</div>
<table class="ref-table">
<thead>
<tr>
<th>Concept</th>
<th>Command / Call</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr><td>Escape analysis</td><td>go build -gcflags="-m" ./...</td><td>Shows what escapes to heap</td></tr>
<tr><td>Verbose escape</td><td>go build -gcflags="-m=2" ./...</td><td>Shows why each decision was made</td></tr>
<tr><td>Disable inlining</td><td>go build -gcflags="-l" ./...</td><td>For debugging; not for production</td></tr>
<tr><td>Inlining decisions</td><td>go build -gcflags="-m" ./...</td><td>"can inline" / "inlining call to"</td></tr>
<tr><td>CPU profile (HTTP)</td><td>/debug/pprof/profile?seconds=30</td><td>Requires import _ "net/http/pprof"</td></tr>
<tr><td>Heap profile (HTTP)</td><td>/debug/pprof/heap</td><td>Current in-use allocations</td></tr>
<tr><td>Goroutine dump</td><td>/debug/pprof/goroutine</td><td>Stack traces of all goroutines</td></tr>
<tr><td>Analyze profile</td><td>go tool pprof -http=:8081 cpu.prof</td><td>Web flame graph</td></tr>
<tr><td>Bench + profile</td><td>go test -bench=. -cpuprofile=cpu.prof</td><td>Profile a benchmark</td></tr>
<tr><td>Compare benchmarks</td><td>benchstat before.txt after.txt</td><td>golang.org/x/perf/cmd/benchstat</td></tr>
<tr><td>Object pool</td><td>sync.Pool{New: func() any { … }}</td><td>GC may evict any time; always Reset</td></tr>
<tr><td>String build</td><td>strings.Builder + Grow(n)</td><td>Single allocation at String()</td></tr>
<tr><td>Pre-alloc slice</td><td>make([]T, 0, n)</td><td>Avoids reallocation in append loop</td></tr>
<tr><td>Pre-alloc map</td><td>make(map[K]V, n)</td><td>Fewer rehash events</td></tr>
<tr><td>Struct size</td><td>unsafe.Sizeof(T{})</td><td>Order fields largest-first to reduce padding</td></tr>
<tr><td>Goroutine count</td><td>runtime.NumGoroutine()</td><td>Monitor for leaks</td></tr>
<tr><td>Detect leaks in tests</td><td>goleak.VerifyNone(t)</td><td>go.uber.org/goleak</td></tr>
<tr><td>Force no inlining</td><td>//go:noinline directive</td><td>Above the function declaration</td></tr>
<tr><td>Alloc-free int→str</td><td>strconv.AppendInt(buf[:0], n, 10)</td><td>Appends to existing buffer</td></tr>
<tr><td>GC before profile</td><td>runtime.GC()</td><td>Accurate heap snapshot</td></tr>
</tbody>
</table>
</section>
</main>
<nav class="toc-nav">
<div class="toc-title">On this page</div>
<ul class="toc">
<li><a href="#stack-heap">1: Stack vs Heap</a></li>
<li><a href="#pprof">2: pprof Profiling</a></li>
<li><a href="#allocations">3: Reducing Allocations</a></li>
<li><a href="#inlining">4: Inlining</a></li>
<li><a href="#goroutine-leaks">5: Goroutine Leaks</a></li>
<li><a href="#memory">6: Memory Efficiency</a></li>
<li><a href="#benchmarks">7: Benchmark Output</a></li>
<li><a href="#reference">99: Quick Reference</a></li>
</ul>
</nav>
</div>
</body>
</html>