Rag*_*ghu 12 memory-management go
我在Go中实现了一个HTTP服务器.
对于每个请求,我需要为特定的结构创建数百个对象,我有~10个这样的结构.因此,根据Go实现完成请求后,它将被垃圾收集.
因此,对于每个请求,将分配和释放大量内存.
相反,我想实现内存池以提高分配端和GC端的性能
在请求开始时,我将从池中取出并在请求提供后将其放回
从池实现方面
在内存分配和释放的情况下,还有其他任何提高性能的建议吗?
icz*_*cza 24
事先注意:
许多人建议使用sync.Pool哪种是临时对象的快速,良好的实现.但请注意,这sync.Pool并不能保证池化对象得以保留.引用其文档:
存储在池中的任何项目都可以随时自动删除,恕不另行通知.如果池在发生这种情况时保留唯一引用,则可以取消分配该项.
因此,如果您不希望Pool收集垃圾中的对象(这取决于您的情况可能导致更多分配),下面提供的解决方案会更好,因为通道缓冲区中的值不是垃圾收集的.如果您的对象真的那么大,那么内存池是合理的,池通道的开销将被摊销.
此外,sync.Pool不允许您限制池化对象的数量,而下面介绍的解决方案自然会这样做.
最简单的内存池"实现"是缓冲通道.
假设你想要一些大对象的内存池.创建一个缓冲通道,指向指向这些昂贵对象的值的指针,无论何时需要,都从池(通道)接收一个.使用完毕后,将其放回池中(在频道上发送).为避免意外丢失对象(例如,遇到恐慌),请defer在放回时使用声明.
让我们使用它作为我们的大对象的类型:
type BigObject struct {
Id int
Something string
}
Run Code Online (Sandbox Code Playgroud)
创建池是:
pool := make(chan *BigObject, 10)
Run Code Online (Sandbox Code Playgroud)
池的大小就是通道缓冲区的大小.
使用昂贵对象的指针填充池(这是可选的,请参阅末尾的注释):
for i := 0; i < cap(pool); i++ {
bo := &BigObject{Id: i}
pool <- bo
}
Run Code Online (Sandbox Code Playgroud)
使用许多goroutines的池:
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
bo := <-pool
defer func() { pool <- bo }()
fmt.Println("Using", bo.Id)
fmt.Println("Releasing", bo.Id)
}()
}
wg.Wait()
Run Code Online (Sandbox Code Playgroud)
在Go Playground尝试一下.
请注意,如果正在使用所有"池化"对象,则此实现会阻止.如果您不想这样做,您可以使用select强制创建新对象(如果所有对象都在使用中):
var bo *BigObject
select {
case bo = <-pool: // Try to get one from the pool
default: // All in use, create a new, temporary:
bo = &BigObject{Id:-1}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您无需将其放回池中.或者,如果游泳池中有空间而没有阻挡,您可以选择尝试将所有物品放回池中,同样select:
select {
case pool <- bo: // Try to put back into the pool
default: // Pool is full, will be garbage collected
}
Run Code Online (Sandbox Code Playgroud)
笔记:
事先填充池是可选的.如果您select尝试从/向池中获取/返回值,则池最初可能为空.
您必须确保不在请求之间泄漏信息,例如,确保您不使用已设置且属于其他请求的共享对象中的字段和值.
Grz*_*Żur 13
这是sync.Pool@JimB提到的实现.注意将defer对象返回池的用法.
package main
import "sync"
type Something struct {
Name string
}
var pool = sync.Pool{
New: func() interface{} {
return &Something{}
},
}
func main() {
s := pool.Get().(*Something)
defer pool.Put(s)
s.Name = "hello"
// use the object
}
Run Code Online (Sandbox Code Playgroud)