Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mm-go

> 编程语言
Open source

Generic manual memory management for golang

194 stars0 likes0 views
WebsiteGitHub

About

Generic manual memory management for golang

mm-go Generic manual memory management for golang

Golang manages memory via GC and it's good for almost every use case but sometimes it can be a bottleneck. and this is where mm-go comes in to play.

Before using mm-go

  • Golang doesn't have any way to manually allocate/free memory, so how does mm-go allocate/free? It does so via cgo.
  • Before considering using this try to optimize your program to use less pointers, as golang GC most of the time performs worse when there is a lot of pointers, if you can't use this lib.
  • Manual memory management provides better performance (most of the time) but you are 100% responsible for managing it (bugs, segfaults, use after free, double free, ....)
  • Don't mix Manually and Managed memory (example if you put a slice in a manually managed struct it will get collected because go GC doesn't see the manually allocated struct, use Vector instead)
  • All data structures provided by the package are manually managed and thus can be safely included in manually managed structs without the GC freeing them, but you have to free them yourself!
  • Try to minimize calls to cgo by preallocating (using batchallocator/Arena/AllocMany).
  • Check the docs, test files and read the README.

Star History

Installing

go get -u github.com/joetifa2003/mm-go

At a glance

…

mm-go is built around the concept of Allocators, which is an interface that can be implemented and passed around to the library. You use these allocators to allocate memory, and also allocate datastructures like vectors, linkedlists, hashmaps, etc.

Benchmarks

Check the test files and github actions for the benchmarks (linux, macos, windows). mm-go can sometimes be 5-10 times faster.

…

mm

go
import "github.com/joetifa2003/mm-go"

Index

  • func SizeOf[T any]() int
  • func Zero[T any]() T

func SizeOf

go
func SizeOf[T any]() int

SizeOf returns the size of T in bytes

Example

go
fmt.Println(mm.SizeOf[int32]())
fmt.Println(mm.SizeOf[int64]())
// Output:
// 4
// 8

Output

4
8

func Zero

go
func Zero[T any]() T

Zero returns a zero value of T

allocator

go
import "github.com/joetifa2003/mm-go/allocator"

Example

go
package main

import (
	"fmt"

	"github.com/joetifa2003/mm-go/allocator"
)

func main() {
	alloc := allocator.NewC()
	defer alloc.Destroy()

	ptr := allocator.Alloc[int](alloc)
	defer allocator.Free(alloc, ptr)

	*ptr = 15
	fmt.Println(*ptr)

}

Output

15

Example (Datastructures)

…

Output

{100 200}
15
70
hello
world

Index

  • func Alloc[T any](a Allocator) *T
  • func AllocMany[T any](a Allocator, n int) []T
  • func Free[T any](a Allocator, ptr *T)
  • func FreeMany[T any](a Allocator, slice []T)
  • func Realloc[T any](a Allocator, slice []T, newN int) []T
  • type Allocator
    • func NewAllocator(allocator unsafe.Pointer, alloc func(allocator unsafe.Pointer, size int) unsafe.Pointer, free func(allocator unsafe.Pointer, ptr unsafe.Pointer), realloc func(allocator unsafe.Pointer, ptr unsafe.Pointer, size int) unsafe.Pointer, destroy func(allocator unsafe.Pointer)) Allocator
    • func NewC() Allocator
    • func (a Allocator) Alloc(size int) unsafe.Pointer
    • func (a Allocator) Destroy()
    • func (a Allocator) Free(ptr unsafe.Pointer)
    • func (a Allocator) Realloc(ptr unsafe.Pointer, size int) unsafe.Pointer

func Alloc

go
func Alloc[T any](a Allocator) *T

Alloc allocates T and returns a pointer to it.

Example

go
alloc := allocator.NewC()
defer alloc.Destroy()

// So you can do this:
ptr := allocator.Alloc[int](alloc) // allocates a single int and returns a ptr to it
defer allocator.Free(alloc, ptr)   // frees the int (defer recommended to prevent leaks)
*ptr = 15
fmt.Println(*ptr)

// instead of doing this:
ptr2 := (*int)(alloc.Alloc(mm.SizeOf[int]()))
defer alloc.Free(unsafe.Pointer(ptr2))
*ptr2 = 15

fmt.Println(*ptr2)

// Output:
// 15
// 15

Output

15
15

func AllocMany

go
func AllocMany[T any](a Allocator, n int) []T

AllocMany allocates n of T and returns a slice representing the heap. CAUTION: don't append to the slice, the purpose of it is to replace pointer arithmetic with slice indexing

Example

…

Output

45
70

func Free

go
func Free[T any](a Allocator, ptr *T)

FreeMany frees memory allocated by Alloc takes a ptr CAUTION: be careful not to double free, and prefer using defer to deallocate

func FreeMany

go
func FreeMany[T any](a Allocator, slice []T)

FreeMany frees memory allocated by AllocMany takes in the slice (aka the heap) CAUTION: be careful not to double free, and prefer using defer to deallocate

func Realloc

go
func Realloc[T any](a Allocator, slice []T, newN int) []T

Realloc reallocates memory allocated with AllocMany and doesn't change underling data

Example

go
package main

import (
	"fmt"

	"github.com/joetifa2003/mm-go/allocator"
)

func main() {
	alloc := allocator.NewC()
	defer alloc.Destroy()

	heap := allocator.AllocMany[int](alloc, 2) // allocates 2 int and returns it as a slice of ints with length 2

	heap[0] = 15
	heap[1] = 70

	heap = allocator.Realloc(alloc, heap, 3)
	heap[2] = 100

	fmt.Println(heap[0])
	fmt.Println(heap[1])
	fmt.Println(heap[2])

	allocator.FreeMany(alloc, heap)

}

Output

15
70
100

type Allocator

Allocator is an interface that defines some methods needed for most allocators. It's not a golang interface, so it's safe to use in manually managed structs (will not get garbage collected).

go
type Allocator struct {
    // contains filtered or unexported fields
}

func NewAllocator

go
func NewAllocator(allocator unsafe.Pointer, alloc func(allocator unsafe.Pointer, size int) unsafe.Pointer, free func(allocator unsafe.Pointer, ptr unsafe.Pointer), realloc func(allocator unsafe.Pointer, ptr unsafe.Pointer, size int) unsafe.Pointer, destroy func(allocator unsafe.Pointer)) Allocator

NewAllocator creates a new Allocator

Example

…

func NewC

go
func NewC() Allocator

NewC returns an allocator that uses C calloc, realloc and free.

func (Allocator) Alloc

go
func (a Allocator) Alloc(size int) unsafe.Pointer

Alloc allocates size bytes and returns an unsafe pointer to it.

func (Allocator) Destroy

go
func (a Allocator) Destroy()

Destroy destroys the allocator. After calling this, the allocator is no longer usable. This is useful for cleanup, freeing allocator internal resources, etc.

func (Allocator) Free

go
func (a Allocator) Free(ptr unsafe.Pointer)

Free frees the memory pointed by ptr

func (Allocator) Realloc

go
func (a Allocator) Realloc(ptr unsafe.Pointer, size int) unsafe.Pointer

Realloc reallocates the memory pointed by ptr with a new size and returns a new pointer to it.

batchallocator

go
import "github.com/joetifa2003/mm-go/batchallocator"

This allocator purpose is to reduce the overhead of calling CGO on every allocation/free, it also acts as an arena since it frees all the memory when `Destroy` is called. It allocats large chunks of memory at once and then divides them when you allocate, making it much faster. This allocator has to take another allocator for it to work, usually with the C allocator. You can optionally call `Free` on the pointers allocated by batchallocator manually, and it will free the memory as soon as it can. `Destroy` must be called to free internal resources and free all the memory allocated by the allocator.

Example

…

Example (Arena)

…

Output

15
70
hello
world

Index

  • func New(a allocator.Allocator, options ...BatchAllocatorOption) allocator.Allocator
  • type BatchAllocator
  • type BatchAllocatorOption
    • func WithBucketSize(size int) BatchAllocatorOption

func New

go
func New(a allocator.Allocator, options ...BatchAllocatorOption) allocator.Allocator

New creates a new BatchAllocator and applies optional configuration using BatchAllocatorOption

type BatchAllocator

BatchAllocator manages a collection of memory buckets to optimize small allocations

go
type BatchAllocator struct {
    // contains filtered or unexported fields
}

type BatchAllocatorOption

go
type BatchAllocatorOption func(alloc *BatchAllocator)

func WithBucketSize

go
func WithBucketSize(size int) BatchAllocatorOption

WithBucketSize Option to specify bucket size when creating BatchAllocator You can allocate more memory than the bucketsize in one allocation, it will allocate a new bucket and put the data in it.

Example

go
alloc := batchallocator.New(
	allocator.NewC(),
	batchallocator.WithBucketSize(mm.SizeOf[int]()*15), // configure the allocator to allocate size of 15 ints per bucket.
)
defer alloc.Destroy()

ptr := allocator.Alloc[int](alloc)
defer allocator.Free(alloc, ptr) // this can be removed and the memory will still be freed on Destroy.

ptr2 := allocator.Alloc[int](alloc) // will not call CGO because there is still enough memory in the Bucket.
defer allocator.Free(alloc, ptr2)   // this can be removed and the memory will still be freed on Destroy.

hashmap

go
import "github.com/joetifa2003/mm-go/hashmap"

Example

go
alloc := batchallocator.New(allocator.NewC())
defer alloc.Destroy()

hm := New[int, int](alloc)
defer hm.Free() // can be removed

hm.Set(1, 10)
hm.Set(2, 20)
hm.Set(3, 30)

sumKeys := 0
sumValues := 0
for k, v := range hm.Iter() {
	sumKeys += k
	sumValues += v
}

fmt.Println(sumKeys)
fmt.Println(sumValues)

// Output:
// 6
// 60

Output

6
60

Index

  • type Hashmap
    • func New[K comparable, V any](alloc allocator.Allocator) *Hashmap[K, V]
    • func (hm *Hashmap[K, V]) Delete(key K)
    • func (hm *Hashmap[K, V]) Free()
    • func (hm *Hashmap[K, V]) Get(key K) (value V, exists bool)
    • func (hm *Hashmap[K, V]) GetPtr(key K) (value *V, exists bool)
    • func (hm *Hashmap[K, V]) Iter() iter.Seq2[K, V]
    • func (hm *Hashmap[K, V]) Keys() []K
    • func (hm *Hashmap[K, V]) Set(key K, value V)
    • func (hm *Hashmap[K, V]) Values() []V

type Hashmap

Hashmap Manually managed hashmap,

go
type Hashmap[K comparable, V any] struct {
    // contains filtered or unexported fields
}

func New

go
func New[K comparable, V any](alloc allocator.Allocator) *Hashmap[K, V]

New creates a new Hashmap with key of type K and value of type V

func (*Hashmap[K, V]) Delete

go
func (hm *Hashmap[K, V]) Delete(key K)

Delete delete value with key K

func (*Hashmap[K, V]) Free

go
func (hm *Hashmap[K, V]) Free()

Free frees the Hashmap

func (*Hashmap[K, V]) Get

go
func (hm *Hashmap[K, V]) Get(key K) (value V, exists bool)

Get takes key K and return value V

func (*Hashmap[K, V]) GetPtr

go
func (hm *Hashmap[K, V]) GetPtr(key K) (value *V, exists bool)

GetPtr takes key K and return a pointer to value V

func (*Hashmap[K, V]) Iter

go
func (hm *Hashmap[K, V]) Iter() iter.Seq2[K, V]

Iter returns an iterator over all key/value pairs

func (*Hashmap[K, V]) Keys

go
func (hm *Hashmap[K, V]) Keys() []K

Keys returns all keys as a slice

func (*Hashmap[K, V]) Set

go
func (hm *Hashmap[K, V]) Set(key K, value V)

Set inserts a new value V if key K doesn't exist, Otherwise update the key K with value V

func (*Hashmap[K, V]) Values

go
func (hm *Hashmap[K, V]) Values() []V

Values returns all v

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gogolangmallocmemory-management

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言