How to implement Memory Pooling in Golang

前端 未结 2 2007
予麋鹿
予麋鹿 2020-12-02 14:39

I implemented an HTTP server in Go.

For each request, I need to create hundreds of objects for a particular struct, and I have ~10 structs like that. So after the re

2条回答
  •  孤街浪徒
    2020-12-02 15:35

    This is the sync.Pool implementation mentioned by @JimB. Mind the usage of defer to return object to pool.

    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
    }
    

提交回复
热议问题