1

Preface

sync.Pool is a temporary object pool, which stores temporary objects. You cannot use it to store socket long connections and database connection pools.

sync.Pool is essentially used to save and reuse temporary objects to reduce memory allocation and reduce GC pressure. For example, if you need to use an object, go to the pool to get it, and if you can’t get it, allocate a copy. This is compared to constantly generating new ones. It is much more efficient to wait for the GC to reclaim the object when it is used up.

sync.Pool

sync.Pool is very simple, look at the sample code:

package student

import (
    "sync"
)

type student struct {
    Name string
    Age  int
}

var studentPool = &sync.Pool{
    New: func() interface{} {
        return new(student)
    },
}

func New(name string, age int) *student {
    stu := studentPool.Get().(*student)
    stu.Name = name
    stu.Age = age
    return stu
}

func Release(stu *student) {
    stu.Name = ""
    stu.Age = 0
    studentPool.Put(stu)
}

When using the student object, you only need to call the New() method to get the object, and then use the defer function to release it.

stu := student.New("tom", 30)
defer student.Release(stu)

// 业务逻辑
...

The actual release of the objects in sync.Pool

summary

  1. Be sure to store temporary objects!
  2. We must pay attention to Get later, to call Put !

The above, I hope it can help you.

Recommended reading


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang