How to Use Arenas (arena Package) for Manual Memory Management in Go

Use the Go arena package with the goexperiment.arenas tag to manually allocate and free bulk memory blocks for better performance.

Use the arena package to allocate objects in a shared memory block and free them all at once to reduce garbage collection pressure. Enable the feature with the goexperiment.arenas build tag, create an arena, allocate values using arena.New or arena.MakeSlice, and call arena.Free when done.

//go:build goexperiment.arenas

package main

import "arena"

type Data struct {
	Value int
}

func main() {
	a := arena.NewArena()
	defer a.Free()

	// Allocate a struct in the arena
	d := arena.New[Data](a)
	d.Value = 42

	// Allocate a slice in the arena
	s := arena.MakeSlice[int](a, 0, 100)

	// Use d and s here...
	// Memory is freed automatically when a.Free() runs
}