ch8/

directory
v0.0.0-...-3bfe4c5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2025 License: MIT

README

Go Memory Management Examples

This folder contains code examples from the chapter on memory management in Go, focusing on garbage collection, stack and heap allocation, and memory optimization techniques.

Table of Contents

Memory Ballast

Memory ballast is used to artificially inflate the heap size to optimize the behavior of the garbage collector (GC).

ballast := make([]byte, 10<<30)

Memory Arenas

Memory arenas are a useful tool for allocating objects from a contiguous region of memory and freeing them all at once with minimal memory management overhead.

Importing the Arena Package

First, import the arena package:

import "arena"
Creating a New Arena

Create a new arena:

mem := arena.NewArena()
Allocating a New Reference for a Struct in the Arena

Allocate a new reference for a struct type in the arena:

p := arena.New[Person](mem)
Creating a Slice with a Predetermined Capacity in the Arena

Create a slice with a predetermined capacity in the arena:

slice := arena.MakeSlice[string](mem, 100, 100)
Freeing the Arena

Free the arena to deallocate all objects at once:

mem.Free()
Cloning an Object from the Arena to the Heap

Clone an object from the arena to the heap:

p1 := arena.New[Person](mem) // arena-allocated
p2 := arena.Clone(p1) // heap-allocated
Using the Address Sanitizer

Use the address sanitizer to detect issues with memory access after freeing the arena:

type T struct {
    Num int
}
func main() {
    mem := arena.NewArena()
    o := arena.New[T](mem)
    mem.Free()
    o.Num = 123 // <- this is a problem
}

Run the program with the address sanitizer:

go run -asan main.go

GC Environment Variables

GODEBUG

The GODEBUG environment variable provides insights into the inner workings of the Go runtime, including garbage collection processes.

Enable GC tracing:

export GODEBUG=gctrace=1
GOGC

The GOGC environment variable controls the aggressiveness of the garbage collection process.

Set GOGC to run GC more frequently:

export GOGC=50
GOMEMLIMIT

The GOMEMLIMIT environment variable sets a soft memory limit for the Go runtime.

Set a memory limit:

export GOMEMLIMIT=500MiB

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL