Go语言学习技巧之如何合理使用Pool
作者:Zachary Marv 时间:2024-02-05 08:04:47
前言
Go 1.3 的sync包中加入一个新特性:Pool。
这个类设计的目的是用来保存和复用临时对象,以减少内存分配,降低CG压力。
type Pool
func (p *Pool) Get() interface{}
func (p *Pool) Put(x interface{})
New func() interface{}
垃圾回收一直是Go语言的一块心病,在它执行垃圾回收的时间中,你很难做什么。
在垃圾回收压力大的服务中,GC占据的CPU有可能超过2%,造成的Pause经常超过2ms。垃圾严重的时候,秒级的GC也出现过。
如果经常临时使用一些大型结构体,可以用Pool来减少GC。
示例代码
package main
import (
"fmt"
"sync"
"time"
)
type structR6 struct {
B1 [100000]int
}
var r6Pool = sync.Pool{
New: func() interface{} {
return new(structR6)
},
}
func usePool() {
startTime := time.Now()
for i := 0; i < 10000; i++ {
sr6 := r6Pool.Get().(*structR6)
sr6.B1[0] = 0
r6Pool.Put(sr6)
}
fmt.Println("pool Used:", time.Since(startTime))
}
func standard() {
startTime := time.Now()
for i := 0; i < 10000; i++ {
var sr6 structR6
sr6.B1[0] = 0
}
fmt.Println("standard Used:", time.Since(startTime))
}
func main() {
standard()
usePool()
}
一个含有100000个int值的结构体,在标准方法中,每次均新建,重复10000次,一共需要耗费193ms;
如果用完的struct可以废物利用,放回pool中。需要新的结构体的时候,尝试去pool中取,而不是重新生成,重复10000次仅需要693us。
这样简单的操作,却节约了99.65%的时间,也节约了各方面的资源。最重要的是它可以有效减少GC CPU和GC Pause。
来源:http://zablog.me/2017/12/13/go_pool/
标签:go语言,使用pool
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于mysql主备切换canal出现的问题解决
2024-01-28 14:29:08
CSS框架/命名/规则 注意要点
2008-06-03 13:07:00
python实现感知器
2021-03-18 09:12:13
![](https://img.aspxhome.com/file/2023/0/91980_0s.png)
BootStrap modal实现拖拽功能
2024-04-18 09:43:48
在HTML中,常见的URL有多种表示方式:
2009-07-28 12:18:00
解析PHP中empty is_null和isset的测试
2023-11-18 17:39:06
python实现计算图形面积
2021-06-01 06:18:54
![](https://img.aspxhome.com/file/2023/7/75967_0s.jpg)
Python中的Pandas 时间函数 time 、datetime 模块和时间处理基础讲解
2022-08-01 05:18:41
![](https://img.aspxhome.com/file/2023/9/63559_0s.png)
Python 面向对象编程详解
2023-06-25 05:24:23
python保留小数位的三种实现方法
2021-09-05 22:36:09
Python利用随机函数生成变化图形详解
2021-07-02 06:54:54
![](https://img.aspxhome.com/file/2023/6/77586_0s.jpg)
Java实现从数据库导出大量数据记录并保存到文件的方法
2024-01-16 09:47:37
大容量csv快速内导入sqlserver的解决方法(推荐)
2024-01-13 00:44:12
python根据给定文件返回文件名和扩展名的方法
2023-09-04 03:41:07
Python基于pygame实现的font游戏字体(附源码)
2021-04-16 05:06:17
![](https://img.aspxhome.com/file/2023/2/72062_0s.png)
Python实现批量下载ts文件并合并为mp4
2022-07-15 20:24:09
![](https://img.aspxhome.com/file/2023/0/70110_0s.png)
浅谈numpy.where() 的用法和np.argsort()的用法说明
2022-03-12 01:52:23
![](https://img.aspxhome.com/file/2023/7/99077_0s.png)
sql在一个表中添加字段并添加备注的方法
2024-01-26 10:16:59
Python 静态方法和类方法实例分析
2021-07-08 19:25:37
![](https://img.aspxhome.com/file/2023/3/131573_0s.png)
sql ROW_NUMBER()与OVER()方法案例详解
2024-01-12 21:34:32
![](https://img.aspxhome.com/file/2023/5/71715_0s.png)