针对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.
go get -u github.com/joetifa2003/mm-go…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.
Check the test files and github actions for the benchmarks (linux, macos, windows). mm-go can sometimes be 5-10 times faster.
…import "github.com/joetifa2003/mm-go"func SizeOf[T any]() intSizeOf returns the size of T in bytes
Example
fmt.Println(mm.SizeOf[int32]())
fmt.Println(mm.SizeOf[int64]())
// Output:
// 4
// 84
8func Zero[T any]() TZero returns a zero value of T
import "github.com/joetifa2003/mm-go/allocator"Example
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)
}15Example (Datastructures)
…{100 200}
15
70
hello
worldfunc Alloc[T any](a Allocator) *TAlloc allocates T and returns a pointer to it.
Example
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
// 1515
15func AllocMany[T any](a Allocator, n int) []TAllocMany 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
…45
70func 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[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[T any](a Allocator, slice []T, newN int) []TRealloc reallocates memory allocated with AllocMany and doesn't change underling data
Example
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)
}15
70
100Allocator 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).
type Allocator struct {
// contains filtered or unexported fields
}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)) AllocatorNewAllocator creates a new Allocator
Example
…func NewC() AllocatorNewC returns an allocator that uses C calloc, realloc and free.
func (a Allocator) Alloc(size int) unsafe.PointerAlloc allocates size bytes and returns an unsafe pointer to it.
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 (a Allocator) Free(ptr unsafe.Pointer)Free frees the memory pointed by ptr
func (a Allocator) Realloc(ptr unsafe.Pointer, size int) unsafe.PointerRealloc reallocates the memory pointed by ptr with a new size and returns a new pointer to it.
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)
…15
70
hello
worldfunc New(a allocator.Allocator, options ...BatchAllocatorOption) allocator.AllocatorNew creates a new BatchAllocator and applies optional configuration using BatchAllocatorOption
BatchAllocator manages a collection of memory buckets to optimize small allocations
type BatchAllocator struct {
// contains filtered or unexported fields
}type BatchAllocatorOption func(alloc *BatchAllocator)func WithBucketSize(size int) BatchAllocatorOptionWithBucketSize 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
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.import "github.com/joetifa2003/mm-go/hashmap"Example
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
// 606
60Hashmap Manually managed hashmap,
type Hashmap[K comparable, V any] struct {
// contains filtered or unexported fields
}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 (hm *Hashmap[K, V]) Delete(key K)Delete delete value with key K
func (hm *Hashmap[K, V]) Free()Free frees the Hashmap
func (hm *Hashmap[K, V]) Get(key K) (value V, exists bool)Get takes key K and return value V
func (hm *Hashmap[K, V]) GetPtr(key K) (value *V, exists bool)GetPtr takes key K and return a pointer to value V
func (hm *Hashmap[K, V]) Iter() iter.Seq2[K, V]Iter returns an iterator over all key/value pairs
func (hm *Hashmap[K, V]) Keys() []KKeys returns all keys as a slice
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 (hm *Hashmap[K, V]) Values() []VValues returns all v
暂无开放 Issues,或尚未同步最近议题。