GoLang sync.Pool簡介與用法
使用場景
一句話總結:保存和復用臨時對象,減少內(nèi)存分配,降低GC壓力
sync.Pool
是可伸縮的,也是并發(fā)安全的,其大小僅受限于內(nèi)存大小。sync.Pool
用于存儲那些被分配了但是沒有使用,而未來可能會使用的值。這樣就可以不用再次經(jīng)過內(nèi)存分配,可直接復用已有對象,減輕GC的壓力,從而提升系統(tǒng)性能。
使用方法
聲明對象池
type Student struct { Name string Age int32 Remark [1024]byte } func main() { var studentPool = sync.Pool{ New: func() interface{} { return new(Student) }, } }
Get & Put
type Student struct { Name string Age int32 Remark [1024]byte } var buf, _ = json.Marshal(Student{Name: "lxy", Age: 18}) func Unmarsh() { var studentPool = sync.Pool{ New: func() interface{} { return new(Student) }, } stu := studentPool.Get().(*Student) err := json.Unmarshal(buf, stu) if err != nil { return } studentPool.Put(stu) }
Get()
用于從對象池中獲取對象,因為返回值是interface{}
,因此需要類型轉換Put()
則是在對象使用完畢之后,返回對象池
性能測試
以下是性能測試的代碼:
package benchmem import ( "encoding/json" "sync" "testing" ) type Student struct { Name string Age int32 Remark [1024]byte } var buf, _ = json.Marshal(Student{Name: "lxy", Age: 18}) var studentPool = sync.Pool{ New: func() interface{} { return new(Student) }, } func BenchmarkUnmarshal(b *testing.B) { for n := 0; n < b.N; n++ { stu := &Student{} json.Unmarshal(buf, stu) } } func BenchmarkUnmarshalWithPool(b *testing.B) { for n := 0; n < b.N; n++ { stu := studentPool.Get().(*Student) json.Unmarshal(buf, stu) studentPool.Put(stu) } }
輸入以下命令:
go test -bench . -benchmem
以下是性能測試的結果:
goos: windows
goarch: amd64
pkg: ginTest
cpu: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
BenchmarkUnmarshal-8 17004 74103 ns/op 1392 B/op 8 allocs/op
BenchmarkUnmarshalWithPool-8 17001 71173 ns/op 240 B/op 7 allocs/op
PASS
ok ginTest 3.923s
在這個例子中,因為 Student 結構體內(nèi)存占用較小,內(nèi)存分配幾乎不耗時間。而標準庫 json 反序列化時利用了反射,效率是比較低的,占據(jù)了大部分時間,因此兩種方式最終的執(zhí)行時間幾乎沒什么變化。但是內(nèi)存占用差了一個數(shù)量級,使用了 sync.Pool
后,內(nèi)存占用僅為未使用的 240/1392 = 1/6
,對 GC 的影響就很大了。
我們甚至在fmt.Printf
的源碼里面也使用了sync.Pool
進行性能優(yōu)化!
到此這篇關于GoLang sync.Pool簡介與用法的文章就介紹到這了,更多相關GoLang sync.Pool內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Golang實現(xiàn)對網(wǎng)絡數(shù)據(jù)包的捕獲與分析
在網(wǎng)絡通信中,網(wǎng)絡數(shù)據(jù)包是信息傳遞的基本單位,抓包是一種監(jiān)控和分析網(wǎng)絡流量的方法,用于獲取網(wǎng)絡數(shù)據(jù)包并對其進行分析,本文將介紹如何使用Golang實現(xiàn)抓包功能,包括網(wǎng)絡數(shù)據(jù)包捕獲和數(shù)據(jù)包分析,需要的朋友可以參考下2023-11-11Golang實現(xiàn)Java虛擬機之解析class文件詳解
這篇文章主要為大家詳細介紹了Golang實現(xiàn)Java虛擬機之解析class文件的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-01-01