Go语言优化内存分配的新提案arena,你怎么看?

3,842

Go 语言社区正在讨论关于 arena的新提案。

据悉,arena 是一种从连续的内存区域分配一组内存对象的方法,它的优势在于从 arena 分配对象通常比一般内存分配更有效。而且,arena 中的对象能够用最少的内存管理或垃圾回收开销一次性释放所有内容。

通常情况下,arena 不会在具备垃圾回收的编程语言中实现,因为它们用于显式释放 arena 内存的操作不安全,不符合垃圾回收语义。但是该提案中使用了动态检查来确保 arena 操作是安全的。同时,如果该操作不安全,程序将在不正确的行为发生之前终止。

目前 Go 团队已在 Google 内部实现并使用了 arena,使用结果是它为众多大型应用程序节省了高达 15% 的 CPU 和内存使用量,起到主要作用的是垃圾回收 CPU 时间和堆内存使用量减少了很多。

提案简介

Go团队计划在 Go 标准库中增加一个新的arena包,arena包可用于分配任意数量的 arena,可以从 arena 的内存中分配任意类型的对象,并且 arena 会根据需要自动增长大小。

当 arena 中的所有对象不再使用时,可以显式释放该 arena ,来回收其内存,而无需进行常见的垃圾回收操作。

同时会提供安全检查,如果 arena 操作不安全,程序将在任何不正确的行为发生之前终止。 同时为了保证灵活性,API可以分配任何类型的对象和切片。

提案 API

package arena

type Arena struct {
        // contains filtered or unexported fields
}

// New allocates a new arena.
func New() *Arena

// Free frees the arena (and all objects allocated from the arena) so that
// memory backing the arena can be reused fairly quickly without garbage
// collection overhead.  Applications must not call any method on this
// arena after it has been freed.
func (a *Arena) Free()

// New allocates an object from arena a.  If the concrete type of objPtr is
// a pointer to a pointer to type T (**T), New allocates an object of type
// T and stores a pointer to the object in *objPtr.  The object must not
// be accessed after arena a is freed.
func (a *Arena) New(objPtr interface{})

// NewSlice allocates a slice from arena a.  If the concrete type of slicePtr
// is *[]T, NewSlice creates a slice of element type T with the specified
// capacity whose backing store is from the arena a and stores it in
// *slicePtr. The length of the slice is set to the capacity.  The slice must
// not be accessed after arena a is freed.
func (a *Arena) NewSlice(slicePtr interface{}, cap int)

用法示例:

import (
        “arena”
        …
)

type T struct {
        val int
}

func main() {
        a := arena.New()
        var ptrT *T
        a.New(&ptrT)
        ptrT.val = 1

        var sliceT []T
        a.NewSlice(&sliceT, 100)
        sliceT[99] .val = 4

        a.Free()
}