preface

Sync. Pool is a temporary object Pool. It stores temporary objects and cannot be used to store socket connections and database connection pools.

Sync. Pool is essentially used to store and reuse temporary objects to reduce memory allocation and reduce GC stress. For example, if you need to use an object, go to the Pool and allocate it if you can’t get it. This is much more efficient than constantly generating new objects and waiting for GC to collect them when they run out.

sync.Pool

Sync. Pool is simple to use. Take a 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)
}
Copy the code

When using the student object, you simply 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) // Defer...Copy the code

It is up to the system to determine when objects in sync.Pool are actually released.

summary

  1. Be sure to store temporary objects!
  2. Be carefulGetAfter, to callPut

Above, hope to be able to help you.

Recommended reading

  • Go – Uses options design mode
  • Go – json.Unmarshal encountered a pit
  • Go – Two little things to watch out for in development
  • Go-time. RFC3339 Time formatting