CodeBlanks Logo Icon CodeBlanks

GC and memory

Learn the heap vs stack split and escape analysis.

Reducing allocations

GC cost is proportional to the allocation rate and the live heap size. The most effective GC tuning is allocating less:

  • Give slices and maps capacity with make.
  • Reuse temporary buffers with sync.Pool.
  • Avoid needless any conversions (boxing) in hot loops.
  • Pass small structs by value instead of pointer.

Using sync.Pool

An object taken from the pool must be reset before use and put back when done:

var tampon = sync.Pool{New: func() any { return new(bytes.Buffer) }}

b := tampon.Get().(*bytes.Buffer)
b.Reset()
b.WriteString("yanıt")
// ... use it ...
tampon.Put(b)

Not putting back very large buffers keeps a single big request from bloating the pool.

Practice Pooled buffer

Set up a *bytes.Buffer pool with sync.Pool (using the New field). Get one, Reset it, write "merhaba", print the contents and Put it back.

Starter code

main.go
package main

import (
    "bytes"
    "fmt"
    "sync"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "bytes"
    "fmt"
    "sync"
)

var havuz = sync.Pool{New: func() any { return new(bytes.Buffer) }}

func main() {
    b := havuz.Get().(*bytes.Buffer)
    b.Reset()
    b.WriteString("merhaba")
    fmt.Println(b.String())
    havuz.Put(b)
}

Expected output

merhaba

Questions and answers

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

1 What can happen to objects in a <code>sync.Pool</code>?

  • They are copied
  • They can be dropped during GC; the pool isn't a permanent cache Correct answer
  • They are kept forever
  • They are written to disk

Explanation: A pool may empty itself across GC cycles; it suits only temporary objects that can be recreated.

2 Put it back

Question
b := havuz.Get().(*bytes.Buffer)
b.Reset()
// ...
havuz.____(b)
Answer
b := havuz.Get().(*bytes.Buffer)
b.Reset()
// ...
havuz.Put(b)

Explanation: Put leaves the object in the pool; a later Get can reuse it.

3 Technique and gain

Term Meaning
make(..., 0, n) No growth copies
sync.Pool Buffer reuse
Value struct No heap allocation
strings.Builder Few intermediate strings

All lessons in Expert