Go - 使用 sync-Pool 來減少 GC 壓力
文章目錄:
-
前言
-
sync.Pool
-
小結
-
推薦閱讀
前言
sync.Pool
是臨時對象池,存儲的是臨時對象,不可以用它來存儲 socket
長連接和數據庫連接池等。
sync.Pool
本質是用來保存和複用臨時對象,以減少內存分配,降低 GC 壓力,比如需要使用一個對象,就去 Pool 裏面拿,如果拿不到就分配一份,這比起不停生成新的對象,用完了再等待 GC 回收要高效的多。
sync.Pool
sync.Pool
的使用很簡單,看下示例代碼:
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)
}
當使用 student
對象時,只需要調用 New()
方法獲取對象,獲取之後使用 defer
函數進行釋放即可。
stu := student.New("tom", 30)
defer student.Release(stu)
// 業務邏輯
...
關於 sync.Pool
裏面的對象具體是什麼時候真正釋放,是由系統決定的。
小結
-
一定要注意存儲的是臨時對象!
-
一定要注意
Get
後,要調用Put
!
以上,希望對你能夠有所幫助。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/rW8AnP-xAFC9wFrOmf7bPw