(资料图片)
目录
使用场景使用方法声明对象池Get & Put性能测试使用场景
一句话总结:保存和复用临时对象,减少内存分配,降低GC压力
sync.Pool是可伸缩的,也是并发安全的,其大小仅受限于内存大小。sync.Pool用于存储那些被分配了但是没有使用,而未来可能会使用的值。这样就可以不用再次经过内存分配,可直接复用已有对象,减轻GC的压力,从而提升系统性能。
使用方法
声明对象池
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 结构体内存占用较小,内存分配几乎不耗时间。而标准库 json 反序列化时利用了反射,效率是比较低的,占据了大部分时间,因此两种方式最终的执行时间几乎没什么变化。但是内存占用差了一个数量级,使用了 sync.Pool后,内存占用仅为未使用的 240/1392 = 1/6,对 GC 的影响就很大了。
我们甚至在fmt.Printf的源码里面也使用了sync.Pool进行性能优化!
到此这篇关于GoLang sync.Pool简介与用法的文章就介绍到这了,更多相关GoLang sync.Pool内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
关键词:
下一篇:最后一页
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

